Cannot fetch Facebook uploaded images - ios

func fetchListOfUserPhotos() {
// let graphRequest = GraphRequest(graphPath: "me", parameters: ["fields": "picture"])
graphRequest.start(completionHandler: { [self] (_, result, error) in
if error != nil {
print(error as Any)
} else {
print(result)
}
})
}
getting empty data.. please help me to resolve this issue.

Related

From FBSDKGraphRequest to Storyboard

i'm total beginner in coding, but i have a big question :)
I dont know how to get information to display on Main Storyboard form FBSDKGraphRequest.
What i should do next to get picture to Storyboard? I hope someone can help me :)
Using Swift 3, Xcode 8
Facebook login is working and code is:
func getFBUserData(){
if((FBSDKAccessToken.current()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
self.dict = result as? [String : AnyObject]
print(result!)
print(self.dict)
}
})
}
I see it as four steps -- my apologies to you if you already know some of this.
Drag an UIImageView from the object library in interface builder to a view in your storyboard.
Connect the UIImageView to your code as an IBOutlet and name it. Do this by control dragging from your new UIImageView to your code, and then in the popup specify an outlet and name the UIImageView. In my case I named it 'facebookPicture'
Get the URL for the image from the FaceBook result. The following sample code drills down into the result dictionary step by step. There are many ways to shorten this.
#IBOutlet var facebookPicture: UIImageView!
func getFBUserID(){
if((FBSDKAccessToken.current()) != nil) {
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(
completionHandler: {
[weak self] (connection, result, error) -> Void in
guard let strongSelf = self else { return }
if let error = error {
print("Failed to download FB user with error:. \(error)")
}
if (error == nil) {
let resultDictSwift = result as! Dictionary<String, Any>
if let picture = resultDictSwift["picture"] as? Dictionary<String, Any> {
if let pictureData = picture["data"] as? Dictionary<String, Any> {
if let pictureURL = NSURL(string: (pictureData["url"] as? String)! ) {
strongSelf.downloadImage(url: pictureURL as URL)
}
}
}
print(result!)
let FBID = resultDictSwift["id"]
strongSelf.facebookID = FBID as! String?
print("User FB id: \(strongSelf.facebookID!)")
}
})
}
}
Download the image from the URL location. The following does this asynchronously and uses a previous stack overflow answer here When the download is complete, it sets the result of the download to be the image in your UIImageView
func getDataFromUrl(url: URL, completion: #escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url) { data, response, error in
completion(data, response, error)
}.resume()
}
func downloadImage(url: URL) {
print("Download Started")
getDataFromUrl(url: url) { data, response, error in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() {
self.facebookPicture.image = UIImage(data: data)
}
}
}
I hope this helps!
In Swift 3
#IBAction func btnFacebookTapped(_ sender: UIButton)
{
let loginManager = FBSDKLoginManager()
loginManager.logIn(withReadPermissions: ["user_about_me", "email" , "user_birthday","user_hometown"], from: self) { (loginResult, error) in
if error != nil
{
self.showalert(strMessage: (error?.localizedDescription)!)
}
else
{
if loginResult?.grantedPermissions == nil
{
self.showalert(strMessage: "Login Permissions not granted")
return
}
if (loginResult?.grantedPermissions.contains("email"))!
{
self.getFBUserData()
}
}
}
}
func getFBUserData()
{
FBSDKGraphRequest.init(graphPath: "me?fields=id,name,email,first_name,last_name,cover,picture.type(large),gender,birthday,hometown", parameters: nil).start(completionHandler: { (connection , result , error ) in
if(error == nil){
DispatchQueue.main.async {
let dictionary = result as! NSDictionary
print(dictionary)
print("Name : \(dictionary.value(forKey: "name")!)")
print("FB ID : \(dictionary.value(forKey: "id")!)")
}
}else{
self.showalert(strMessage: "Somthig Went Wrong..!")
}
})
}

Unable get Facebook User_birthday, Location in Swift2

Below is my code :-
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager .logInWithReadPermissions(["public_profile","user_birthday","email"], handler: { (result, error) -> Void in
if (error == nil)
{
let fbloginresult : FBSDKLoginManagerLoginResult = result
if(fbloginresult.grantedPermissions.contains("email"))
{
self.getFBUserData()
}
}
})
}
func getFBUserData()
{
if((FBSDKAccessToken.currentAccessToken()) != nil)
{
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture, email, gender, age_range, birthday"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil)
{
print(result)
self.performSegueWithIdentifier("login_with_facebook_vc", sender: nil)
}
})
}
}
I am new in swift2. So i am unable to get facebook user_birthday, location.
Please help me.
I use this code to get email:
func getEmail() {
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("Error: \(error)")
}
else
{
print("fetched user: \(result)")
if let facebookEmail: String = result.valueForKey("email") as? String {
print("email is: \(facebookEmail)")
self.email = facebookEmail
}
}
})
}
Try this with birthday

Can't return output of closure using graph api

If I call this method to obtain a Facebook profile picture it does not work, response gets printed with the data but when I return it its nil, can anyone help?
func getProfilePicture() -> NSData?{
var response:NSData?
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"picture.type(large)"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if error != nil {
print("login error: \(error!.localizedDescription)")
return
}
let json = JSON(result)
let profilePicture = json["picture"]["data"]["url"].stringValue
if let url = NSURL(string: profilePicture) {
if let pictureData = NSData(contentsOfURL: url){
response = pictureData
}
}
})
print(response)
return response
}
The Facebook call is using an async completionblock and your return statement will return nil before the call is done loading. That is why you also should use a completion block in your method.
Here is an example how to do this:
func getProfilePicture(completion: (pictureData: NSData?, error: NSError?) -> Void) {
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"picture.type(large)"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
var pictureData: NSData?
let json = JSON(result)
let profilePicture = json["picture"]["data"]["url"].stringValue
if let url = NSURL(string: profilePicture) {
pictureData = NSData(contentsOfURL: url)
}
completion(pictureData: pictureData, error: error)
})
}
You can call this code like this:
self.getProfilePicture {(pictureData, error) -> Void in
if error != nil {
print("login error: \(error!.localizedDescription)")
}
print(pictureData)
}

Passing parameters for posting an item to Facebook

I have a code for post to Facebook but in parameters I have to add my own but its not working for me.
I have these 3 things to post my Facebook i.e. title, description, date time.
let notSureItem = NotSureItem()
notSureItem.title = self.textField.text!
notSureItem.textDescription = self.textAreaDescription.text!
notSureItem.dateTime = self.dateTime
I have this code for posting to Facebook.
if (FBSDKAccessToken.currentAccessToken() != nil){
if FBSDKAccessToken.currentAccessToken().hasGranted("publish_actions") {
FBSDKGraphRequest(graphPath: "me/feed", parameters: ["message": "hello"], HTTPMethod: "POST").startWithCompletionHandler({
(connection, result, error) -> Void in
if !(error != nil) {
NSLog("Post id:%#", result["id"])
}
})
}
}
In parameters I had passed a message which is successfully post on Facebook but if I had to pass parameters which I had stated above how to do that.
If anyone can help thanks a lot.
This solved my problem. Simply passed as string and its work.
if (FBSDKAccessToken.currentAccessToken() != nil){
if FBSDKAccessToken.currentAccessToken().hasGranted("publish_actions") {
FBSDKGraphRequest(graphPath: "me/feed", parameters: ["message": "\(self.textField.text!)\n \(self.textAreaDescription.text!)\n \(self.dateTime)"], HTTPMethod: "POST").startWithCompletionHandler({
(connection, result, error) -> Void in
if !(error != nil) {
NSLog("Post id:%#", result["id"])
}
})
}
}

iOS facebookSDK get user full details

Iam using the last FBSDK (using swift)
// MARK: sign in with facebook
func signInWithFacebook()
{
if (FBSDKAccessToken.currentAccessToken() != nil)
{
// User is already logged in, do work such as go to next view controller.
println("already logged in ")
self.returnUserData()
return
}
var faceBookLoginManger = FBSDKLoginManager()
faceBookLoginManger.logInWithReadPermissions(["public_profile", "email", "user_friends"], handler: { (result, error)-> Void in
//result is FBSDKLoginManagerLoginResult
if (error != nil)
{
println("error is \(error)")
}
if (result.isCancelled)
{
//handle cancelations
}
if result.grantedPermissions.contains("email")
{
self.returnUserData()
}
})
}
func returnUserData()
{
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
println("Error: \(error)")
}
else
{
println("the access token is \(FBSDKAccessToken.currentAccessToken().tokenString)")
var accessToken = FBSDKAccessToken.currentAccessToken().tokenString
var userID = result.valueForKey("id") as! NSString
var facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large"
println("fetched user: \(result)")
}
when I print the fetched user I get only the id and the name ! ,
but i requested a permission for email and friends and profile ,
what's wrong ???
BTW : I moved this project from my macbook to another macbook ( because I formatted mine) it worked very well when it was at the the macbook which I created the project on , but after moving the project (using bitbucket clone) I got this results .
As per the new Facebook SDK, you must have to pass the parameters with the FBSDKGraphRequest
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
println(result)
}
})
}
Documentations Link : https://developers.facebook.com/docs/facebook-login/permissions/v2.4
User object reference : https://developers.facebook.com/docs/graph-api/reference/user
With public profile you can get gender :
public_profile (Default)
Provides access to a subset of items that are part of a person's public profile. A person's public profile refers to the following properties on the user object by default:
id
name
first_name
last_name
age_range
link
gender
locale
timezone
updated_time
verified
Swift 4
An example in Swift 4 that also shows how to correctly parse out the individual fields from the result:
func fetchFacebookFields() {
//do login with permissions for email and public profile
FBSDKLoginManager().logIn(withReadPermissions: ["email","public_profile"], from: nil) {
(result, error) -> Void in
//if we have an error display it and abort
if let error = error {
log.error(error.localizedDescription)
return
}
//make sure we have a result, otherwise abort
guard let result = result else { return }
//if cancelled nothing todo
if result.isCancelled { return }
else {
//login successfull, now request the fields we like to have in this case first name and last name
FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "first_name, last_name"]).start() {
(connection, result, error) in
//if we have an error display it and abort
if let error = error {
log.error(error.localizedDescription)
return
}
//parse the fields out of the result
if
let fields = result as? [String:Any],
let firstName = fields["first_name"] as? String,
let lastName = fields["last_name"] as? String
{
log.debug("firstName -> \(firstName)")
log.debug("lastName -> \(lastName)")
}
}
}
}
}
I guess this code should help you get the required details
Swift 2.x
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
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 userID : NSString = result.valueForKey("id") as! NSString
print("User Email is: \(userID)")
}
})
In Swift 4.2 and Xcode 10.1
#IBAction func onClickFBSign(_ sender: UIButton) {
if let accessToken = AccessToken.current {
// User is logged in, use 'accessToken' here.
print(accessToken.userId!)
print(accessToken.appId)
print(accessToken.authenticationToken)
print(accessToken.grantedPermissions!)
print(accessToken.expirationDate)
print(accessToken.declinedPermissions!)
let request = GraphRequest(graphPath: "me", parameters: ["fields":"id,email,name,first_name,last_name,picture.type(large)"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion)
request.start { (response, result) in
switch result {
case .success(let value):
print(value.dictionaryValue!)
case .failed(let error):
print(error)
}
}
let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
self.present(storyboard, animated: true, completion: nil)
} else {
let loginManager=LoginManager()
loginManager.logIn(readPermissions: [ReadPermission.publicProfile, .email, .userFriends, .userBirthday], viewController : self) { loginResult in
switch loginResult {
case .failed(let error):
print(error)
case .cancelled:
print("User cancelled login")
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
print("Logged in : \(grantedPermissions), \n \(declinedPermissions), \n \(accessToken.appId), \n \(accessToken.authenticationToken), \n \(accessToken.expirationDate), \n \(accessToken.userId!), \n \(accessToken.refreshDate), \n \(accessToken.grantedPermissions!)")
let request = GraphRequest(graphPath: "me", parameters: ["fields": "id, email, name, first_name, last_name, picture.type(large)"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion)
request.start { (response, result) in
switch result {
case .success(let value):
print(value.dictionaryValue!)
case .failed(let error):
print(error)
}
}
let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
self.navigationController?.pushViewController(storyboard, animated: true)
}
}
}
}
https://developers.facebook.com/docs/graph-api/reference/user

Resources