在 iOS Facebook SDK 中获取并显示用户的个人资料图片

Getting and displaying a user's profile picture in the iOS Facebook SDK

我正在使用 Facebook 的 SDK 允许用户登录我的应用程序,我希望该应用程序显示用户的个人资料图片。我有以下故事板和 Swift 文件:

"Main"包含用户登录的viewcontroller,用户登录的代码如下:

import UIKit
import FacebookLogin

class ViewController: UIViewController
{
    override func viewDidLoad()
    {
        super.viewDidLoad()

        if AccessToken.current != nil
        {
            // Already logged-in
            // Redirect to Home View Controller
            goToHome()
        }

        // Add LoginButton
        let loginButton = FBLoginButton(permissions: [ .publicProfile, .email, .userFriends ])
        let screenSize:CGRect = UIScreen.main.bounds
        let screenHeight = screenSize.height // real screen height
        //let's suppose we want to have 10 points bottom margin
        let newCenterY = screenHeight - loginButton.frame.height - 20
        let newCenter = CGPoint(x: view.center.x, y: newCenterY)
        loginButton.center = newCenter
        view.addSubview(loginButton)

        // Triggered after every successfully login / logout
        NotificationCenter.default.addObserver(forName: .AccessTokenDidChange, object: nil, queue: OperationQueue.main) { [weak self] _ in
            if AccessToken.current != nil {
                // Successfully just Logged in
                // Redirect to Home View Controller
                self?.goToHome()
            } else {
                // Successfully just Logged out
            }
        }
    }

    func goToHome() {
        let storyboard = UIStoryboard(name: "HomeAfterLogIn", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "HomeAfterLogInViewController") // I called mine like that (check screenshot below)
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

此代码显示使用 Facebook 按钮登录,如果用户输入成功登录

func goToHome()

将用户发送到 HomeAfterLogIn.storyboard,这是我希望显示用户个人资料图片的地方。

我在 Facebook 的 Graph API 网站上找到了这段代码:

FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
    initWithGraphPath:@"/100046232170264/picture"
           parameters:@{ @"redirect": @"false",}
           HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
    // Insert your code here
}];

以上数值与我的应用有关。当我将此代码插入我的 HomeAfterLogInViewController.swift 文件时,只会产生以下错误:

我输入的代码有误吗?是Swift之前的版本吗,我的是swift4或者5?这是我第一次使用 Facebook SDK。

评论后 post

(Keshu R.) 将 obj-c 转换为 Swift:

let request = FBSDKGraphRequest(graphPath: "/100046232170264/picture", parameters: [
    "redirect": "false"
], httpMethod: "GET")
request.start(withCompletionHandler: { connection, result, error in
    // Insert your code here
})

(Karol Zmysłowski) 代码错误:

(Keshu R.)UI HomeAfterLogIn.storyboard 项:

import FacebookCore
import FacebookLogin

Profile.loadCurrentProfile(completion: { profile, error in
    if let profile = profile {
        let imageURL = profile.imageURL(forMode: .square, size: CGSize(width: 200.0, height: 200.0))
    }
})

我建议创建一个自定义按钮并向其添加操作

// import 
import FBSDKCoreKit
import FBSDKLoginKit


class LoginVC : UIViewController {
    // create an IBAction and call the function inside it
    @IBAction func facebookLoginBtnPressed(_ sender : Any) {
        fetchFacebookFields()
    }
    // this function will return all the details and you can store it in userdefaults
    func fetchFacebookFields() {
        LoginManager().logIn(permissions: ["email","public_profile"], from: nil) {
            (result, error) -> Void in
            if let error = error {
                print(error.localizedDescription)
                return
            }
            guard let result = result else { return }
            if result.isCancelled { return }
            else {
                GraphRequest(graphPath: "me", parameters: ["fields" : "first_name, last_name, email"]).start() {
                    (connection, result, error) in
                    if let error = error {
                        print(error.localizedDescription)
                        return
                    }
                    if
                        let fields = result as? [String:Any],
                        let userID = fields["id"] as? String,
                        let firstName = fields["first_name"] as? String,
                        let lastName = fields["last_name"] as? String,
                        let email = fields["email"] as? String

                    {
                        let facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large"
                        print("firstName -> \(firstName)")
                        print("lastName -> \(lastName)")
                        print("email -> \(email)")
                        print("facebookProfileUrl -> \(facebookProfileUrl)")
                        APPDELEGATEOBJ.makeRootVC(vcName : "MainTabBarVC")

                    }
                }
            }
        }
    }
}