繁体   English   中英

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

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

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

  • Main.storyboard & ViewController.swift

  • HomeAfterLogIn.storyboard & HomeAfterLogInViewController.swift

“Main”包含用户登录的视图控制器,用户登录的代码如下:

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,这是我希望显示用户个人资料图片的地方。

我在 Facebooks 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,我的是 Swift 4 还是 5? 这是我第一次使用 Facebook SDK。

发表评论后

(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.) HomeAfterLogIn.storyboard 中的 UI 项目:

在此处输入图片说明

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

                    }
                }
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM