Skip to content

Swift Developer Blog

Learn Swift and App Development for iOS

  • Swift Blog
    • UITableView
    • UIImageView
    • UIScrollView
    • UIWebView
    • SubView
    • UIImagePickerController
    • UIPageViewController
    • UITabBarController
    • UIAlertController
    • UISegmentedControl
    • Xcode
    • Firebase
  • Video Tutorials
  • Code Examples
    • Code examples
    • Cheat Sheets
  • Resources
    • Swift Developer
  • Full stack
    • Developer Resources
    • Android & Kotlin
    • Java
    • RESTful Web Services
    • Amazon Web Services
    • Firebase with Kotlin
    • Firebase with Swift
    • Hibernate
    • Git
    • Design Patterns
  • About
  • Contact me
  • Home
  • User login and Registration with Swift
  • Parse Login with Facebook account. Example in Swift.
July 28, 2015 by Sergey Kargopolov 18 comments on "Parse Login with Facebook account. Example in Swift."

Parse Login with Facebook account. Example in Swift.

In this video tutorial I am going to share with you how to integrate Facebook SDK for iOS platform into your Swift mobile app that uses Parse Cloud Service as it’s app back end.

If you are interested to learn how to implement features User Sign up, Sign in, Password reset, Email verification, Profile details update together with Left Side Sliding Navigation menu and other features with Swift and Parse SDK for iOS, please check out my video course which will guide you through implementation of these features step by step and will save you a lot of time 🙂 https://goo.gl/DJ5TG4

Integrate Facebook SDK for iOS platform and Parse SDK for iOS platform into Swift project

AppDelegate source code:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        
        Parse.setApplicationId("YOU APP ID", clientKey: "YOUR CLIENT KEY")
        
       PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
        
        return true
    }
    
    
    func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
        
        return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
    }

    func applicationWillResignActive(application: UIApplication) {
    
    }

    func applicationDidEnterBackground(application: UIApplication) {
 
    }

    func applicationWillEnterForeground(application: UIApplication) {
 
    }

    func applicationDidBecomeActive(application: UIApplication) {
 
         FBSDKAppEvents.activateApp()
        
    }

    func applicationWillTerminate(application: UIApplication) {
        
    }

Implement Facebook Login and Logout buttons 

Facebook Sign in button tapped function source code:

   @IBAction func signInButtonTapped(sender: AnyObject) {
        
        
        PFFacebookUtils.logInInBackgroundWithReadPermissions(["public_profile","email"], block: { (user:PFUser?, error:NSError?) -> Void in
            
            if(error != nil)
            {
              //Display an alert message
                var myAlert = UIAlertController(title:"Alert", message:error?.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert);
                
                let okAction =  UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
                
                myAlert.addAction(okAction);
                self.presentViewController(myAlert, animated:true, completion:nil);
                
                return
            }
            
            println(user)
            println("Current user token=\(FBSDKAccessToken.currentAccessToken().tokenString)")
            
            println("Current user id \(FBSDKAccessToken.currentAccessToken().userID)")
            
            if(FBSDKAccessToken.currentAccessToken() != nil)
            {
               let protectedPage = self.storyboard?.instantiateViewControllerWithIdentifier("ProtectedPageViewController") as! ProtectedPageViewController
                
                let protectedPageNav = UINavigationController(rootViewController: protectedPage)
                
                let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                
                appDelegate.window?.rootViewController = protectedPageNav
             
            }
       })
        
    }

Load Facebook user profile details and store it in Parse Users Class

Load Facebook user profile details and store them in Parse Users Class

      var requestParameters = ["fields": "id, email, first_name, last_name"]
        
        let userDetails = FBSDKGraphRequest(graphPath: "me", parameters: requestParameters)
        
        userDetails.startWithCompletionHandler { (connection, result, error:NSError!) -> Void in
    
            if(error != nil)
            {
                println("\(error.localizedDescription)")
               return
            }
            
            if(result != nil)
            {
            
                let userId:String = result["id"] as! String
                let userFirstName:String? = result["first_name"] as? String
                let userLastName:String? = result["last_name"] as? String
                let userEmail:String? = result["email"] as? String
                
                
                println("\(userEmail)")
                
                let myUser:PFUser = PFUser.currentUser()!
                
                // Save first name
                if(userFirstName != nil)
                {
                    myUser.setObject(userFirstName!, forKey: "first_name")
                    
                }
                
                //Save last name
                if(userLastName != nil)
                {
                    myUser.setObject(userLastName!, forKey: "last_name")
                }
                
                // Save email address
                if(userEmail != nil)
                {
                    myUser.setObject(userEmail!, forKey: "email")
                }
                
               dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
                
                // Get Facebook profile picture
                var userProfile = "https://graph.facebook.com/" + userId + "/picture?type=large"
                
                let profilePictureUrl = NSURL(string: userProfile)
                
                let profilePictureData = NSData(contentsOfURL: profilePictureUrl!)
                
                if(profilePictureData != nil)
                {
                    let profileFileObject = PFFile(data:profilePictureData!)
                    myUser.setObject(profileFileObject, forKey: "profile_picture")
                }
                
                
                myUser.saveInBackgroundWithBlock({ (success:Bool, error:NSError?) -> Void in
                  
                    if(success)
                    {
                        println("User details are now updated")
                    }
                    
                })
                
                }
               
            }
        
        }
        

Download source code to entire project

Posted in: Facebook SDK and Swift, User login and Registration with Swift
Tagged: Facebook SDK, Facebook Sign in, Parse

Post navigation

Previous Previous post: Facebook SDK for iOS – Login & Logout example with Swift
Next Next post: UICollectionView example in Swift

Primary Sidebar

Find videos

Unit Testing Swift?

Unit Testing Swift Mobile App

Recent Posts

  • Inject JavaScript into WKWebView
  • WKWebView. Load HTML File from App Bundle.
  • UIImagePickerController in Swift with Firebase. Cheat Sheet.
  • Firebase Realtime Database Cheat Sheet
  • Push Notifications with Firebase Cloud Messaging – Cheat Sheet

Search by Tag

AWS Facebook Facebook SDK Facebook Sign in Firebase HTTP HTTP Get HTTP Post Icon Java Keychain Load Images Login MMDrawerController MySQL Navigation Drawer NSURLSession Parse Password PHP Push Notifications Search Sign in SubView Swift UIActivityIndicator UIAlertController UIImage UIImagePickerController UIImageView UIPageViewController UIScrollView UISearchBar UISegmentedControl UITabBarController UITableView UITableViewCell UITableViewController UITableViewDatasource UIWebView Upload Xcode Xcode Tips Xcode Tips and Tricks XIB

Featured posts

  • Left side menu (Navigation Drawer) example with Swift
  • Creating custom user interface files with XIB in Xcode 6 and Swift
  • Add Subview and Remove subview example in Swift
  • Customize UINavigationBar appearance in Swift
  • MBProgressHUD example in Swift
  • iOS Keychain example in Swift
  • Image Upload with Progress Bar example in Swift
  • Circular Image or Image with Rounded Corners. Example in Swift

Copyright © 2023 Swift Developer Blog. Powered by WordPress and Themelia.

Would you like more video tutorials weekly?
  • Swift programming with Parse. Practical Examples.
  • Swift programming with PHP and MySQL. Practical examples.
  • iOS Mobile Apps Development with Swift

Enter your email and stay on top of things,

Subscribe!