Skip to content

Instantly share code, notes, and snippets.

@tsraveling
Last active April 25, 2017 18:47
Show Gist options
  • Save tsraveling/ab6c657cc5797b09fb5a5b623e95bb83 to your computer and use it in GitHub Desktop.
Save tsraveling/ab6c657cc5797b09fb5a5b623e95bb83 to your computer and use it in GitHub Desktop.
Facebook Integration
import FacebookCore
import FacebookCore
let connection = GraphRequestConnection()
connection.add(GraphRequest(graphPath: "/me")) { httpResponse, result in
switch result {
case .success(let response):
print("Graph Request Succeeded: \(response)")
case .failed(let error):
print("Graph Request Failed: \(error)")
}
}
connection.start()
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb<#T##app key#></string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string><#T##app key#></string>
<key>FacebookDisplayName</key>
<string><#T##app name#></string>
import FBSDKLoginKit
FBSDKLoginManager().logOut()
FBSDKAccessToken.setCurrent(nil)
FBSDKProfile.setCurrent(nil)

Setting up Facebook in a Swift project

1. Add to pods:

pod 'FacebookCore'
pod 'FacebookLogin'
pod 'FacebookShare'

pod install

2. Modify info.plist

Copy the included snippet, then add fbauth2 to LSApplicationQueriesSchemes.

3. Add platform to Facebook app under Settings

iOS -> add bundle id, turn on single sign on.

4. Modify App Delegate

Import:

import FBSDKCoreKit

Add to didFinishLaunchingWithOptions:

// Set up Facebook
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

Add to applicationDidBecomeActive:

FBSDKAppEvents.activateApp()

Add:

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    let sourceApplication: String? = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String
    return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: sourceApplication, annotation: nil)
}

5. Trigger login thusly:

let loginManager = LoginManager()
loginManager.logIn([ .PublicProfile ], viewController: self) { loginResult in
  switch loginResult {
  case .Failed(let error): 
    print(error)
  case .Cancelled:
    print("User cancelled login.")
  case .Success(let grantedPermissions, let declinedPermissions, let accessToken):
    print("Logged in!")
}

6. Thereafter get token thusly:

if let accessToken = AccessToken.current {
    // User is logged in, use 'accessToken' here.
    print("We are Facebook logged in")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment