Facebook sdk integration using SWIFT in iPhone application


To integrate the Facebook SDK using swift language, follow the below steps:
  • Download the latest Facebook sdk at https://developers.facebook.com/docs/ios/getting-started.
  • Create a application at Facebook, made necessary changes at plist file. All guided documentation is available at https://developers.facebook.com/docs/ios/getting-started
  • Add FacebookSDK.Framework to your project.
  • Create a bridging header by follow the below steps (Bridging header is useful when you want to access objective-c code in your swift language).
  • Create a new Objective-C header file by clicking File->New.
  • Give it a name (BridgingHeader.h).
  • Write the import statement in your bridge header file.
#import <FacebookSDK/FacebookSDK.h>
  • Goto build settings for your target, find "Swift Compiler – Code Generation" section.
  • Set “Objective-C Bridging Header” to <#PROJECT_NAME>/Bridging-Header.h.
  • “Install Objective-C Compatibility Header”, should be set to “Yes”.
  • Open  AppDelegate.swift and write the below code
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObjectAnyObject]?) -> Bool {
        FBLoginView.self
        FBProfilePictureView.self
        return true
    }

    func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
        let appString : String = sourceApplication!
        println(sourceApplication)
        return FBAppCall.handleOpenURL(url, sourceApplication:sourceApplication)

    }
  • Add the FBLoginViewDelegate methods to your ViewController.swift as below

    func loginViewShowingLoggedInUser(loginView : FBLoginView!) {
        println("User Logged In")
    }
    
    func loginViewFetchedUserInfo(loginView : FBLoginView!, user: FBGraphUser) {
        println("User: \(user)")
        println("User ID: \(user.id)")
        println("User Name: \(user.name)")
        var userEmail = user.objectForKey("email"asString
        println("User Email: \(userEmail)")
    }
    
    func loginViewShowingLoggedOutUser(loginView : FBLoginView!) {
        println("User Logged Out")
    }
    
    func loginView(loginView : FBLoginView!, handleError:NSError) {
        println("Error: \(handleError.localizedDescription)")
    } 

  • Create an IBOutlet of UIView which is of class FBLoginView.
    @IBOutlet var fbLoginView : FBLoginView!


  • Override the viewDidLoad methods as follow:
    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.fbLoginView.delegate = self
        self.fbLoginView.readPermissions = ["public_profile""email""user_friends"]

    }

  • Now run the application.

Comments

Popular posts from this blog

Vector graphics in iOS

Exception Handling - Objective C

How to show activity indicator in watch kit