Hot on the tail of the iOS 10 release, Apple also updated Swift to version 3 and Xcode to 8.0. Facebook’s SDK for Swift can be a little tricky to set up with all this so here’s a quick run-through of all the things I am aware of at this time.
The Facebook Swift SDK
First of all, I’ve used Cocoapods to import the Facebook SDK so my Podfile includes ‘FacebookCore’, ‘FacebookLogin’ and ‘FacebookShare’. There’s plenty of examples out there for setting this up if you are unfamiliar with Cocoapods and I highly recommend it as a way to manage all your imports so they can be easily updated.
Facebook have been slow to update their documentation for the latest release and it’s not always clear which version they are referring too but you can find their examples here – https://developers.facebook.com/docs/swift
First up, let’s look at the AppDelegate
Obviously
import FacebookCore
Then the following functions
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
And
public func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return SDKApplicationDelegate.shared.application(application, open:url, sourceApplication:sourceApplication, annotation:annotation)
}
This is simplified code specifically related to the Facebook SDK, you will likely have further content in the first function above. The second function is what allows the Facebook login window to close and return to your application. This seems to be a common problem for people as it’s missed (at time of writing) from the documentation.
To create a login button for your app that runs the Facebook login process you can use the following code:
let loginButton = LoginButton(readPermissions: [.publicProfile,.email])
loginButton.frame = CGRect(x: 20, y: view.frame.height - 190, width: view.frame.width - 40, height: 50)
loginButton.delegate = self
view.addSubview(loginButton)
Wherever you use the loginButton as above, don’t forget to import the FacebookLogin library at the top of the file. Your class will also need to be of type ‘LoginButtonDelegate’. This will mean adding two further functions to that file:
func loginButtonDidCompleteLogin(_ loginButton: LoginButton, result: LoginResult) {
switch result {
case .failed(let error):
print(error)
case .cancelled:
print("Cancelled")
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
print("Logged In")
}
}
func loginButtonDidLogOut(_ loginButton: LoginButton) {
print("Logged Out")
}
For the purposes of my application it made sense to roll a custom function to retrieve the data I was after at any point. It looks a little something like this:
func facebookLogin() {
if let accessToken = AccessToken.current {
let params = ["fields":"name,email"]
let graphRequest = GraphRequest(graphPath: "me", parameters: params)
graphRequest.start { (urlResponse, requestResult) in
switch requestResult {
case .failed(let error):
print(error)
case .success(let graphResponse):
if let responseDictionary = graphResponse.dictionaryValue {
UserDefaults.standard.set(responseDictionary, forKey: "userInfo")
}
}
}
} else {
}
}
This is a basic call to retrieve the logged in users name and email address from the graph. You can make your call more complex if you have further requirements and obviously use the data you retrieve in any way.
I hope this is useful for anyone who, like me, struggled to get this latest series of updates working for release into the App Store. You can keep up to date with the development of the Facebook Swift SDK on their GitHub page – https://github.com/facebook/facebook-sdk-swift
As a final note, please be aware that it would seem that Apple will reject an App that requires Facebook Login. I provided an option to skip login (with reduced functionality) and that was no problem, but this may not be an option for you so it’s worth considering the options available as an alternative, most likely rolling you own login system using the users email address and a custom password.
I have followed your advice but i got an error from appdalegate
Without you posting your error I can’t really help you. Perhaps if you post it below then we can answer your problem?
first of all i have to tell you that i’m a newbie for swift .
this happened after i clicked on the fb login button.
thank you so much.
https://drive.google.com/file/d/0B9y4mwiRGz9tMUUwVjFZaEtGMlE/view?usp=sharing
I would think the answer to that error lies in the console window at the bottom right. If you could scroll up a few lines there’ll probably be some more descriptive error or explanation of what actually caused the crash. Maybe if you could display the entire log file I can figure it out for you 🙂
works perfectly, thanks!
You’re very welcome 🙂 Thanks for visiting
pretty colours
Awesome! Worked like a charm
Thanks very much for this guide! I too am struggling to figure out how to use Facebook’s API with Swift. I followed your steps but for some reason am unable to get an AccessToken, and the Login button doesn’t change to “Logout” as it sounds like it should. Any tips? https://codeshare.io/d6Cb9
Have you added the required entries to your info.plist file? You need to add FacebookAppID and FacebookDisplayName. I’m guessing that the problem here is that it’s not authenticating correctly with your Facebook App so that would definitely be where I would start. Hope you find a solution 🙂
i am facing issue in in swift sdk , Safari does not redirect to app after facebook login. It instead tries to open redirect uri in browser
https://github.com/facebook/facebook-sdk-swift/issues/118
using the syntax below for opening url silences depracation warning in AppDelegate:
return SDKApplicationDelegate.shared.application(application, open: url, options: [UIApplicationOpenURLOptionsKey.sourceApplication: sourceApplication!])