SwiftDeveloper SwiftDeveloper - 20 days ago 14
Swift Question

How to get Facebook User id, email, picture.type(large) in Swift 3

Hello I try to get user

id, email, picture.type(large),updated_time
from
Facebook SDK
, i success get all of them but i didnt get picture gives me


Error Cannot call value of non-function type 'Any?!'


My clear codes under below.

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


This line gives error;


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


Also picture object json data example here;

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


Im using
Xcode 8.1
and
Swift 3.0


Thank you !

Answer

This requires simple parsing .. "picture" is Dictionary and so is "data". so something like below works for you

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