Facebook iOS SDK and swift: how get user's profile picture
The profile picture is in fact public and you can simply by adding the user id to Facebook's designated profile picture url address, ex:
var userID = user["id"] as NSString
var facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large"
This particular url address should return the "large" version of the user's profile picture, but several more photo options are available in the docs.
If you want to get the picture in the same request as the rest of the users information you can do it all in one graph request. It's a little messy but it beats making another request.
A more Swift 3 approach
let request = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email, picture.type(large)"])
let _ = request?.start(completionHandler: { (connection, result, error) in
guard let userInfo = result as? [String: Any] else { return } //handle the error
//The url is nested 3 layers deep into the result so it's pretty messy
if let imageURL = ((userInfo["picture"] as? [String: Any])?["data"] as? [String: Any])?["url"] as? String {
//Download image from imageURL
}
})
Swift 2
let request = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email, picture.type(large)"])
request.startWithCompletionHandler({ (connection, result, error) in
let info = result as! NSDictionary
if let imageURL = info.valueForKey("picture")?.valueForKey("data")?.valueForKey("url") as? String {
//Download image from imageURL
}
})
With Facebook SDK 4.0, you can use:
Swift:
let pictureRequest = FBSDKGraphRequest(graphPath: "me/picture?type=large&redirect=false", parameters: nil)
pictureRequest.startWithCompletionHandler({
(connection, result, error: NSError!) -> Void in
if error == nil {
println("\(result)")
} else {
println("\(error)")
}
})
Objective-C:
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:@"me/picture?type=large&redirect=false"]
parameters:nil
HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if (!error){
NSLog(@"result: %@",result);}
else {
NSLog(@"result: %@",[error description]);
}}];