如何在facebook ios中获取访问令牌

时间:2016-07-29 11:24:24

标签: ios swift facebook

我正在iOS中开发一个用于Facebook登录的应用程序。我可以用Facebook登录,但我无法获得访问令牌。

这是我的委托方法:

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)
}

通过我的viewcontroller,我在Facebook登录的故事板中有一个按钮。 这是我的内容按钮:

@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)
            } 
         }

我注意到的一件事是,当我登录Facebook时,它不会在appDelegate中调用application() method。它也没有在我的代码loginView.delegate = self中添加一行。这可能是我的问题的原因,我不知道如何根据我的代码添加该行。

当我尝试通过此行获取访问令牌时:

 var token = FBSDKAccessToken.currentAccessToken().tokenString
 print(token)

我收到此错误:

  

致命错误:在解包可选值时意外发现nil

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您可以使用委托方法:

- (void)fbDialogLogin:
(NSString *)
token expirationDate:(NSDate *)
expirationDate