iOS Swift Facebook SDK 4 getting user profile picture outputs "Question Mark" - ios

I am not an expert in programming, but I modified a code to get the user profile picture from Facebook SDK. The problem is I am getting a Question Mark in the image (profilePicture.image). Can anyone tell me what is going on here?
Also, I am not sure what how to call this function to get image in viewController? At present I am directly adding profilePicture.image inside the function.
func getProfPic(fid: String) -> UIImage? {
if (fid != "") {
var imgURLString = "http://graph.facebook.com/" + fid + "/picture?type=large" //type=normal
var imgURL = NSURL(string: imgURLString)
var imageData = NSData(contentsOfURL: imgURL!)
var image = UIImage(data: imageData!)
profilePicture.image = image // Returned image is Question mark
return image
}
return nil
}

Create a dictionary :
class ViewController: UIViewController {
var dict : NSDictionary!
}
Fetching the data :
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
self.dict = result as NSDictionary
println(self.dict)
NSLog(self.dict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as String)
}
})
}
Output should be :
{
email = "ashishkakkad8#gmail.com";
"first_name" = Ashish;
id = 910855688971343;
"last_name" = Kakkad;
name = "Ashish Kakkad";
picture = {
data = {
"is_silhouette" = 0;
url = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xfa1/v/t1.0-1/s200x200/22501_915701971820048_9046303472199214595_n.jpg?oh=f3b3564f1450c13332b3067a135cad5d&oe=55C71792&__gda__=1443571904_c4667dcb08d85682edfd77a90ee9c3ab";
};
};
}
2015-05-25 22:12:34.015 SwiftFB[2713:7830] https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xfa1/v/t1.0-1/s200x200/22501_915701971820048_9046303472199214595_n.jpg?oh=f3b3564f1450c13332b3067a135cad5d&oe=55C71792&__gda__=1443571904_c4667dcb08d85682edfd77a90ee9c3ab
Convert Image from URL
if let url = NSURL(string: "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xfa1/v/t1.0-1/s200x200/22501_915701971820048_9046303472199214595_n.jpg?oh=f3b3564f1450c13332b3067a135cad5d&oe=55C71792&__gda__=1443571904_c4667dcb08d85682edfd77a90ee9c3ab") {
if let data = NSData(contentsOfURL: url){
yourImageview.image = UIImage(data: data)
}
}

Related

How to fetch facebook's profile picture?

I'm trying to fetch the user's fb profile pic but wasn't able to do so far. I'm trying to do something simple: the user log in with fb account and the app goes to another view where appears his name, email and profile picture. User's name and email are okay, but I can't get the picture!
The app is crashing with my actual code because apparently I'm unwrapping a nil optional value, but I don't know why it's nil.
My code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id,email,name,picture.width(480).height(480)"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("Error: \(error)")
}
else
{
print("fetched user: \(result)")
let userName : NSString = result.valueForKey("name") as! NSString
print("User Name is: \(userName)")
let userEmail : NSString = result.valueForKey("email") as! NSString
print("User Email is: \(userEmail)")
let id = result.valueForKey("id") as! String
self.nameLabel.text = userName as String
self.emailLabel.text = userEmail as String
self.profilePic.image = self.getProfPic(id)
}
})
}
func getProfPic(fid: String) -> UIImage? {
if (fid != "") {
let imgURLString = "http://graph.facebook.com/" + fid + "/picture?type=large" //type=normal
let imgURL = NSURL(string: imgURLString)
let imageData = NSData(contentsOfURL: imgURL!)
let image = UIImage(data: imageData!) // CODE CRASHES IN HERE
return image
}
return nil
}
From your comments I understand that it crashes at the image assigning, you should be doing it with the conditional binding methodology of Swift (if let) in order to avoid unwrapping a nil optional value:
if let data = result["picture"]?["data"]
{
if let url = data["url"] as? String
{
profilePictureURL = url
}
}
Also, as you can see I am not using the valueForKey method.

Get Photo URL Given a Photo ID: Facebook Graph API for iOS (Swift)

My problem boils down to this: fetch a photo URL given a photo ID. Ultimately, I need to do this for all of the photos a user of my iOS app is tagged in. I am able to get the IDs of the photos with the code:
// Create request for user's Facebook data
let request = FBSDKGraphRequest(graphPath:"me", parameters:["fields": "photos"])
request.startWithCompletionHandler {
(connection, result, error) in
if error != nil { }
else if let userData = result as? [String:AnyObject] {
let userPhotos = userData["photos"]
}
}
In the returned user data, I have access to the ID of each photo. Now, I defined a function which should (ideally) return the URL of a photo given it's ID. However, I really do not know how to correctly call the Facebook Graph API. This is what I have (note: hardcoded photo ID).
// Create request for user's Facebook data
let request = FBSDKGraphRequest(graphPath:"/{photo-id}?id=xxxxxxxxxxxxxxxxx", parameters:["fields": "link"])
request.startWithCompletionHandler {
(connection, result, error) in
if error != nil { }
else if let userData = result as? [String:AnyObject] {
let link = userData["link"]
print(link)
}
}
I'm quite confident the the graphPath parameter is wildly wrong. I made some "intelligent" guesses based on this: https://developers.facebook.com/docs/graph-api/reference/photo/
Any help you could give me would be much appreciated. Thanks!
Ok here is a simple answer, thanks for the answer above #user2585945
import UIKit
class FacePhotosViewController: UIViewController{
#IBOutlet weak var imgTest: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
if (FBSDKAccessToken.currentAccessToken() != nil)
{
print("We are good!")
}
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"photos,picture"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("Error: \(error)")
}
else
{
print(result)
let resultdict = result.objectForKey("photos") as! NSDictionary
let data : NSArray = resultdict.objectForKey("data") as! NSArray
for i in 0..<data.count {
let valueDict : NSDictionary = data[i] as! NSDictionary
let id = valueDict.objectForKey("id") as! String
let created_time = valueDict.objectForKey("created_time") as! String
print("id: \(id) created_time: \(created_time) ")
}
}
})
let graphRequestPhoto : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "10156292340905363?type=large", parameters: ["fields":"picture, name, album, place"])
graphRequestPhoto.startWithCompletionHandler({ (connection, result, error) -> Void in
print(result)
if ((error) != nil)
{
// Process error
print("Error: \(error)")
}
else if let userData = result as? [String:AnyObject] {
let url = userData["picture"] as? String
print("link: \(url)")
let imgURL: NSURL! = NSURL(string: url!)
//lets' download profile photo
let session = NSURLSession.sharedSession()//session
let request: NSURLRequest = NSURLRequest(URL: imgURL!)//request
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in //session calls the request
if let noerror = data {
dispatch_async(dispatch_get_main_queue()) {
let image = UIImage(data: noerror)
self.imgTest.image = image
}
}
else {
print("Error: \(error!.localizedDescription)", terminator: "")
}
}
dataTask.resume()
}
})
}
}
let requestPhotos = FBSDKGraphRequest(graphPath:id_num, parameters:["fields":"picture, name, album, place"])
Where id_num is the ID number of the Facebook photo. Very simple.

Circular UIImage from FBSDK xcode swift

I have a profile picture which I am taking from a URL from facebook graph request that I am trying to make into a circular profile picture but it is appearing like this:
I don't want it to be pointing at the top, I just want a perfect circle.
This is my code:
#IBOutlet var imageURL: UIImageView!
func returnUserData()
{
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id,email,name,picture.width(50).height(50)"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("Error: \(error)")
}
else
{
print("fetched user: \(result)")
let userID : NSString = result.valueForKey("id") as! NSString
let userName : NSString = result.valueForKey("name") as! NSString
print("User Name is: \(userName)")
let userEmail : NSString = result.valueForKey("email") as! NSString
print("User Email is: \(userEmail)")
let facebookProfileUrl = "https://graph.facebook.com/\(userID)/picture?type=large"
print("\(facebookProfileUrl)")
let url = NSURL(string:facebookProfileUrl)
let data = NSData(contentsOfURL:url!)
if data == nil {
} else {
self.imageURL.layer.borderWidth=1.0
self.imageURL.layer.masksToBounds = false
self.imageURL.layer.borderColor = UIColor.whiteColor().CGColor
self.imageURL.layer.cornerRadius = 15
self.imageURL.layer.cornerRadius = self.imageURL.frame.size.height/2
self.imageURL.clipsToBounds = true
self.imageURL.image = UIImage(data:data!)
}
}
})
}
Apparently your input image isn't square. Crop the top and bottom (or extend the sides) to make it square, then the rest should work.

How to get the cover photo from Facebook + Swift + Parse

I have a log in system in my app swift 2.0 integrated with Facebook, I'm able to get some user informations and profile_picture.
I'm wondering how to get the cover Image from the User logged :
let requestParameters = ["fields": "id, email, first_name, last_name, name, gender, cover"]
let userDetails = FBSDKGraphRequest(graphPath: "me", parameters: requestParameters)
userDetails.startWithCompletionHandler { (connection, result, error:NSError!) -> Void in
if(error != nil)
{
print("\(error.localizedDescription)")
return
}
if(result != nil)
{
let userId:String = result["id"] as! String
let userFirstName:String? = result["first_name"] as? String
let userLastName:String? = result["last_name"] as? String
let userEmail:String? = result["email"] as? String
let userName:String? = result["name"] as? String
let userGender:String? = result["gender"] as? String
let userCover:UIImage? = result["cover"] as? UIImage
print(requestParameters)
print(userDetails)
print(userCover)
print("\(userEmail)")
let myUser:PFUser = PFUser.currentUser()!
// Save first name
if(userFirstName != nil)
{
myUser.setObject(userFirstName!, forKey: "firstNameColumn")
}
//Save last name
if(userLastName != nil)
{
myUser.setObject(userLastName!, forKey: "lastNameColumn")
}
// Save email address
if(userEmail != nil)
{
myUser.setObject(userEmail!, forKey: "email")
}
// Save email address
if(userGender != nil)
{
if (userGender == "male"){
myUser.setObject("Masculino", forKey: "genderColumn")
} else {
myUser.setObject("Feminino", forKey: "genderColumn")
}
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// Get Facebook profile picture
let userProfile = "https://graph.facebook.com/" + userId + "/picture?type=large"
let profilePictureUrl = NSURL(string: userProfile)
let profilePictureData = NSData(contentsOfURL: profilePictureUrl!)
if(profilePictureData != nil)
{
let profileFileObject = PFFile(data:profilePictureData!)
myUser.setObject(profileFileObject!, forKey: "photoUserColumn")
}
myUser.saveInBackgroundWithBlock({ (success:Bool, error:NSError?) -> Void in
if(success)
{
print("User details are now updated")
}
})
}
This code its not working just for the cover Image.
Any ideas?
Here's a working example using fb sdk in swift. I posted this answer in the other question as well but because this answer came up first for me on google I thought it'll be nice to put it here as well.
I needed to get the cover photo of a page so in the graphPath I used page id. This parameter can be easily changed to fit users / events / etc...
let request = FBSDKGraphRequest(graphPath: "\\(page.id)?fields=cover", parameters: [
"access_token": "your_access_token"
], HTTPMethod: "GET")
request.startWithCompletionHandler({(connection , result , error) in
if ((error) != nil) {
print("Error in fetching cover photo for \\(page.id): \(error)", terminator: "")
}
else {
if let data = result["cover"] as? NSDictionary {
self.fetchImageFromUrl(data["source"] as! String, cb: {(image: UIImage) -> Void in
//do something with image
})
}
})
func fetchImageFromUrl(url: String, cb: (UIImage) -> Void) {
let urlObj = NSURL(string: url)!
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let data = NSData(contentsOfURL: urlObj)
dispatch_async(dispatch_get_main_queue(), {
let image = UIImage(data: data!)!
cb(image)
});
}
}
P.S - I'm a newbie in swift / ios so this code might not be the best. Comments will be appreciated.
It can be useful.
let emailRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email,name, id,cover"], tokenString: result?.token.tokenString, version: nil, httpMethod: "GET")
_ = emailRequest?.start(completionHandler: { (nil, resultParameters, error) in
if(error == nil) {
if let cover = (params?["cover"] as? NSDictionary)["source"]{
var coverUrl = cover as? String
}
}
})

Facebook graph object/entity parsing SDK 4 in Swift

In Swift how do you parse the result of a fbk graph request? I have a nested dictionary and casting to [String: String] does not work. I have casted to NSDictionary which works for level 1 but anything nested started complaining about optionals and casting. I see from the changeling that FBGraphObject has been deprecated, so what is the correct approach now in SDK 4?
My data looks like
{
data = {
"is_silhouette" = 0;
url = "...";
};
}
I can do
var data = photoRes["data"] as? NSDictionary
to get
Optional({
"is_silhouette" = 0;
url = "...;
})
I'm not sure how to parse that object...
EDIT For now I have it working with
var data = photoRes["data"] as? NSDictionary
var urlStr = data!["url"] as? String
if urlStr != nil {
let url = NSURL(fileURLWithPath: urlStr!)
//my code...
}
But this is a complicated approach especially if the result coming back is highly nested. Is there a better way to go about this?
Create a dictionary :
class ViewController: UIViewController {
var dict : NSDictionary!
}
Fetching the data :
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
self.dict = result as NSDictionary
println(self.dict)
NSLog(self.dict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as String)
}
})
}
Output should be :
{
email = "ashishkakkad8#gmail.com";
"first_name" = Ashish;
id = 910855688971343;
"last_name" = Kakkad;
name = "Ashish Kakkad";
picture = {
data = {
"is_silhouette" = 0;
url = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xfa1/v/t1.0-1/s200x200/22501_915701971820048_9046303472199214595_n.jpg?oh=f3b3564f1450c13332b3067a135cad5d&oe=55C71792&__gda__=1443571904_c4667dcb08d85682edfd77a90ee9c3ab";
};
};
}
2015-05-25 22:12:34.015 SwiftFB[2713:7830] https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xfa1/v/t1.0-1/s200x200/22501_915701971820048_9046303472199214595_n.jpg?oh=f3b3564f1450c13332b3067a135cad5d&oe=55C71792&__gda__=1443571904_c4667dcb08d85682edfd77a90ee9c3ab
This mess worked for me. I am using SWIFT 3.01 and FB Swift SDK
if let responseDictionary = response.dictionaryValue {
print(responseDictionary["name"] ?? "")
let a = responseDictionary["picture"] as! NSDictionary
let b = a["data"] as! NSDictionary
let c = b["url"]
print(c ?? "")

Resources