在Swift中检索Facebook用户ID

pat*_*g94 6 facebook-graph-api ios swift

我有一个帮助函数,从特定的URL抓取图片:

func getProfilePicture(fid: String) -> UIImage? {
    if (fid != "") {
        var imageURLString = "http://graph.facebook.com/" + fid + "/picture?type=large"
        var imageURL = NSURL(string: imageURLString)
        var imageData = NSData(contentsOfURL: imageURL!)
        var image = UIImage(data: imageData!)
        return image
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)

我继续使用用户的Facebook ID调用getProfilePicture(),并将输出存储到UIImageView中.我的问题是,如何找到Facebook用户的ID?我是否通过Facebook申请连接?如果在这里提供一些代码会很有帮助.

谢谢您的帮助.

Pat*_*ron 8

如果他们已成功登录您的应用:

FBSDKAccessToken.current().userID
Run Code Online (Sandbox Code Playgroud)


dia*_*nms 1

对我有用的:

  1. 使用 FBSDKLoginButtonDelegate
  2. 实现 func loginButtonWillLogin
  3. 将通知添加到 onProfileUpdated
  4. 在 onProfileUpdated 函数中继续获取您的个人资料信息
  5. 调用 onProfileUpdated 后,您可以在任何 Controller 中使用您的 FBSDKProfile

现在,一些 Swift 3 代码......

import UIKit
import FBSDKLoginKit

class ViewController: UIViewController, FBSDKLoginButtonDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    // Facebook login integration
    let logBtn = FBSDKLoginButton()
    logBtn.center = self.view.center
    self.view .addSubview(logBtn)
    logBtn.delegate = self
}

func loginButtonWillLogin(_ loginButton: FBSDKLoginButton!) -> Bool {
    print("will Log In")
    FBSDKProfile.enableUpdates(onAccessTokenChange: true)
    NotificationCenter.default.addObserver(self, selector: #selector(onProfileUpdated(notification:)), name:NSNotification.Name.FBSDKProfileDidChange, object: nil)
    return true
}

func onProfileUpdated(notification: NSNotification)
{
    print("profile updated")
    print("\(FBSDKProfile.current().userID!)")
    print("\(FBSDKProfile.current().firstName!)")
}
}
Run Code Online (Sandbox Code Playgroud)