如何在 Swift 3 中获取 Facebook 用户 ID、电子邮件、图片类型(大)

Posted

技术标签:

【中文标题】如何在 Swift 3 中获取 Facebook 用户 ID、电子邮件、图片类型(大)【英文标题】:How to get Facebook User id, email, picture.type (large) in Swift 3 【发布时间】:2016-11-15 11:41:44 【问题描述】:

我尝试从Facebook SDK 获取用户id, email, picture.type(large),updated_time,我成功获取了所有用户但我没有得到图片 给我:

错误无法调用非函数类型'Any?!'的值

下面是我的清晰代码。

    import UIKit
    import Foundation
    
    class LoginViewController : UIViewController, FBSDKLoginButtonDelegate 
       private var fromLogin = [Login]()
       @IBOutlet weak var loginButton : FBSDKLoginButton!
        
        override func viewDidLoad() 
            super.viewDidLoad()
             // Check Session
            if let token = FBSDKAccessToken.current()
                print(token.tokenString! as Any)
                self.fetchProfile()
            

            loginButton.delegate = self
            loginButton.readPermissions = ["email", "public_profile"]
    

    // Get Profile
    func fetchProfile() 
        print("fetch profile")
        
        // Create facebook graph with fields
         FBSDKGraphRequest(graphpath: "me", parameters: ["fields":"id, name, email, picture.type(large), updated_time"]).start  (connection, result, error) in
            
            // check error
            if error != nil 
                // error happen
                print("Failed to start graph request: \(error?.localizedDescription)")
                return
            
            
            if let userDict = result as? NSDictionary 
                let name = userDict["name"] as? String
                let id = userDict["id"] as? String
                let email = userDict["email"] as? String

                // HERE GIVES ERROR I DIDNT GET PICTURE WITH STRING    
                let userPicture = userDict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as String

                print(userPicture)
                print(name as Any)
                print(id as Any)
                print(email as Any)
        
    


// Delegate Method
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!)
    // check error
    if error != nil 
        // error happen
        print(error?.localizedDescription as Any)
        return
    
    
    print("Successfull login in with facebook...")
    fetchProfile()


func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!)
    print("Log Out")

这一行给出错误;

让 userPicture = userDict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as String

这里也是图片对象json数据示例;

 picture =     
        data =         
            "is_silhouette" = 0;
            url = "https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/14067524_9513823423422249533237851_n.jpg?oh=88eb9b80abbb2342346c01de298&oe=58C5138B";
        ;
    ;

我正在使用Xcode 8.1Swift 3.0

【问题讨论】:

试试下面的答案 @User511 我的代码工作只需要得到图片真实的字符串代码 代码完整。它对我有用。 @User511 userPicture 字符串在哪里?你只打印所有结果 @EICaptainv2.0 兄弟工作得很好你能给出答案吗?我会批准的 【参考方案1】:

这需要简单的解析..“图片”是字典,“数据”也是。所以像下面这样的东西适合你

guard let userDict = result as? [String:Any] else  return 

let name  = userDict["name"] as? String
let id    = userDict["id"] as? String
let email = userDict["email"] as? String

if let picture = userDict["picture"] as? [String:Any] ,  
   let imgData = picture["data"] as? [String:Any] ,   
   let imgUrl = imgData["url"] as? String    
      print(imgUrl)   

【讨论】:

@El Captain v2.0 谢谢你在 Xcode 8.1 和 Swift 3.0 上完美工作【参考方案2】:

替换这个

 FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, name, email, picture.type(large), updated_time"]).start  (connection, result, error) in

FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, name, email, picture.width(500).height(500), updated_time"]).start  (connection, result, error) in

然后检查一下

if let imageUrl = ((dictData.value(forKey: "picture") as? NSDictionary)?.value(forKey: "data") as? NSDictionary)?.value(forKey: "url") as? NSString
                                    
                                        Facebook.imagesArr.add(imageUrl)
                                        print("Pictureasd:",Facebook.imagesArr)
                                    

【讨论】:

【参考方案3】:
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!)
    
        FBSDKGraphRequest.init(graphPath: "me", parameters: ["fields":"first_name, last_name, picture.type(large)"]).start  (connection, result, error) -> Void in

            let strFirstName: String = (result.object(forKey: "first_name") as? String)!
            let strLastName: String = (result.object(forKey: "last_name") as? String)!
            let strPictureURL: String = (result.object(forKey: "picture")?.object(forKey: "data")?.object(forKey: "url") as? String)!

            self.lblName.text = "Welcome, \(strFirstName) \(strLastName)"
            self.ivUserProfileImage.image = UIImage(data: try! Data(contentsOf: URL(string: strPictureURL)!))
        
    

【讨论】:

以上是关于如何在 Swift 3 中获取 Facebook 用户 ID、电子邮件、图片类型(大)的主要内容,如果未能解决你的问题,请参考以下文章

如何从 swift 3 facebook 图形请求中解析这个 JSON

我如何从 facebook 公开资料 Facebook IOS Swift SDK 中获取性别

如何从 Facebook + Swift + Parse 获取封面照片

Facebook iOS SDK 和 swift:如何获取用户的头像

无法在 Xcode Swift Facebook 登录 SDK 中获取访问令牌

Swift 获取 Facebook AccessToken