I am developing an app in iOS for Facebook login. I can log in with Facebook, but I could not get the access token.
This is my delegate method:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject:AnyObject]?) -> Bool {
// Override point for customization after application launch.
print("at delegate")
var configureError: NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
assert(configureError == nil, "Error configuring Google services: \(configureError)")
GIDSignIn.sharedInstance().delegate = self
FBSDKLoginButton.classForCoder()
return FBSDKApplicationDelegate.sharedInstance().application(application,
didFinishLaunchingWithOptions:launchOptions)
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
print("at delegatehg")
return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) || GIDSignIn.sharedInstance().handleURL(url,sourceApplication: sourceApplication,
annotation: annotation)
}
And with my viewcontroller, I have a button in the storyboard for the Facebook login. This my content inside button:
@IBAction func fbLogin(sender: FBSDKLoginButton) {
if (FBSDKAccessToken.currentAccessToken() != nil){
print("token is not nil")
let Level2 = self.storyboard!.instantiateViewControllerWithIdentifier("facebook") as? UIViewController
self.presentViewController(Level2!, animated: true, completion: nil)
} else{
var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.logInWithReadPermissions(["public_profile", "email", "user_friends"], handler: { (result, error) -> Void in
if (error == nil){
var fbloginresult : FBSDKLoginManagerLoginResult = result
if(fbloginresult.grantedPermissions.contains("email"))
{
self.getFBUserData()
fbLoginManager.logOut()
}
}
})
}
}
func getFBUserData(){
FBSDKGraphRequest.init(graphPath: "me", parameters: ["fields":"name,email,picture.type(large),gender"]).startWithCompletionHandler { (connection, result, error) -> Void in
let strName: String = (result.objectForKey("name") as? String)!
print(result)
let Gender : String = (result.objectForKey("gender") as? String)!
let Id = (result.objectForKey("id") as? String)!
let deviceId = UIDevice.currentDevice().identifierForVendor?.UUIDString
let UUID = NSUUID().UUIDString
print(UUID)
var DeviceId = deviceId
print(DeviceId)
print(Id)
print(Gender)
print(strName)
var strEmail : String
if ((result.objectForKey("email") as? String) != nil){
strEmail = (result.objectForKey("email") as? String)!
}else {
strEmail = "not available"
}
//let strEmail: String = (result.objectForKey("email") as? String)!
var userID = result["id"] as! NSString
var facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large"
print(strEmail)
print(strEmail)
let request = NSMutableURLRequest(URL: NSURL(string: "http://projects.svirtzone.com/wified/api/authentication.php")!)
request.HTTPMethod = "POST"
let postString = "username=\(strName)&email=\(strEmail)&action=auth&pic=\(facebookProfileUrl)&dob=1989/05/05&logintype=Facebook&gender=\(Gender)&device_type=Mac&facebookid=\(Id)&agerange=15&deviceid=\(deviceId)&accesstoken=fdfsfs"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
let Level2 = self.storyboard!.instantiateViewControllerWithIdentifier("facebook") as? UIViewController
self.presentViewController(Level2!, animated: true, completion: nil)
if (error == nil){
print(result)
}
}
One thing I noticed is that when I am logging in to Facebook, it doesn't call application() method
in appDelegate. It also did not add a line inside my code loginView.delegate = self
. This may be reason for my problem, and I don't know how to add that line according to my code.
When I try to get access token by this line:
var token = FBSDKAccessToken.currentAccessToken().tokenString
print(token)
I am getting this error:
Fatal error: unexpectedly found nil while unwrapping an Optional value
Can anyone help me please?