Facebook Graph API GET request - Should contain "fields" parameter (Swift, Facebook SDK v4.5.1)

IosXcodeFacebookSwiftFacebook Graph-Api

Ios Problem Overview


My iOS app uses Facebook's Graph API Request during sign up to get user information, which worked fine prior to upgrading to Facebook's newest SDK. After upgrading, I'm getting a runtime error stating: "FBSDKLog: starting with Graph API v2.4, GET requests for /me should contain an explicit "fields" parameter".

Here is the code:

func requestFacebook() {
    
    let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
    graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
        
        if ((error) != nil)
        {
            // Process error
            println("Error: \(error)")
        }
        else if error == nil
        {
            let birthday : NSString = (result.valueForKey("birthday") as? NSString)!
            
            var currentDate = NSDate()
            var birthdayFormatter = NSDateFormatter()
            let userCalendar = NSCalendar.currentCalendar()
            birthdayFormatter.dateFormat = "MM/DD/YYYY"
            var birthdayNSDate = birthdayFormatter.dateFromString(birthday as String)
            
            var userAge = self.calculateAge(birthdayNSDate!)
            
            PFUser.currentUser()!["age"] = userAge
            
            var facebookID: NSString = (result.valueForKey("id") as? NSString)!
            var pictureURL = "https://graph.facebook.com/\(facebookID)/picture?type=large&return_ssl_resources=1"
            
            var URLRequest = NSURL(string: pictureURL)
            var URLRequestNeeded = NSURLRequest(URL: URLRequest!)
            
            NSURLConnection.sendAsynchronousRequest(URLRequestNeeded, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!, error: NSError!) -> Void in
                if error == nil {
                    var picture = PFFile(data: data)
                    PFUser.currentUser()!["picture"] = picture
                    PFUser.currentUser()!.saveInBackgroundWithBlock({ (success, error) -> Void in
                        if error == nil {
                            
                            var userPicture:PFFile = PFUser.currentUser()!.valueForKey("picture") as! PFFile
                            userPicture.getDataInBackgroundWithBlock { (imageData, error) -> Void in
                                if error == nil {
                                    
                                    self.meProfileImageView.image = UIImage(data: imageData!)
                                    var userName:String = PFUser.currentUser()!.valueForKey("username") as! String
                                    var userAge:Int = PFUser.currentUser()!.valueForKey("age") as! Int
                                    self.meLabel.text = "\(userName), \(userAge)"
                                    
                                    self.findFriends()
                                    
                                }
                            }
                            
                        } else {
                            println(error)
                        }
                    })
                }
                else {
                    println("Error: \(error.localizedDescription)")
                }
            })
        }
    })
}

The error message is at the line:

let birthday : NSString = (result.valueForKey("birthday") as? NSString)!

This code ran perfectly fine before upgrading to Facebook's SDK v4.5.1, but I don't know what to change to make this work now. Huge thanks to anyone that can help me!

Ios Solutions


Solution 1 - Ios

this line needs a parameters value that is NOT nil

let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)

I'll expand more, for example, and this is psuedo code of sorts:

so for ObjC it would be this, for example, so the the above would read the following:

parameters:@{@"fields": @"id, name"}

In swift it would be something similar

something like this:

parameters:["fields": "email"]

This is for just two fields, and again it's psuedo code, but you need to specify the parameters


UPDATE:

Im adding this update to show folks where you find the parameters for the fields as described above, here's a quick link:

Here's the Paramters field info (this should stay roughly static with FBSDK, some of this is "core" which means it won't really change that much, but I'll update whenever I can):

https://developers.facebook.com/docs/graph-api/reference/user

The format of the info below is the following, sort of, I just did this quickly:

"parameter" "type"

"description"

> id numeric string > > The id of this person's user account. This ID is unique to each app > and cannot be used across different apps. Our upgrade guide provides > more information about app-specific IDs > > > > about string > > The About Me section of this person's profile > > age_range AgeRange > > The age segment for this person expressed as a minimum and maximum > age. For example, more than 18, less than 21. > > > > bio string > > The person's bio > > birthday string > > The person's birthday. This is a fixed format string, like MM/DD/YYYY. > However, people can control who can see the year they were born > separately from the month and day so this string can be only the year > (YYYY) or the month + day (MM/DD) > > > context UserContext > > Social context for this person > > currency Currency > > The person's local currency information > > devices list > > The list of devices the person is using. This will return only iOS and > Android devices > > education list > > The person's education > > email string > > The person's primary email address listed on their profile. This field > will not be returned if no valid email address is available > > > > favorite_athletes list > > Athletes the person likes > > favorite_teams list > > Sports teams the person likes > > first_name string > > The person's first name > > > > gender string > > The gender selected by this person, male or female. This value will be > omitted if the gender is set to a custom value > > > > hometown Page > > The person's hometown > > inspirational_people list > > The person's inspirational people > > install_type enum > > Install type > > installed bool > > Is the app making the request installed? > > interested_in list > > Genders the person is interested in > > is_shared_login bool > > Is this a shared login (e.g. a gray user) > > is_verified bool > > People with large numbers of followers can have the authenticity of > their identity manually verified by Facebook. This field indicates > whether the person's profile is verified in this way. This is distinct > from the verified field > > languages list > > Facebook Pages representing the languages this person knows > > last_name string > > The person's last name > > > > link string > > A link to the person's Timeline > > > > location Page > > The person's current location as entered by them on their profile. > This field is not related to check-ins > > > > locale string > > The person's locale > > > > meeting_for list > > What the person is interested in meeting for > > **middle_name string > > The person's middle name > > > > name string > > The person's full name > > CoreDefault > > name_format string > > The person's name formatted to correctly handle Chinese, Japanese, or > Korean ordering > > payment_pricepoints PaymentPricepoints > > The person's payment pricepoints > > test_group unsigned int32 > > Platform test group > > political string > > The person's political views > > relationship_status string > > The person's relationship status > > religion string > > The person's religion > > security_settings SecuritySettings > > Security settings > > significant_other User > > The person's significant other > > sports list > > Sports this person likes > > quotes string > > The person's favorite quotes > > third_party_id string > > A string containing an anonymous, but unique identifier for the > person. You can use this identifier with third parties > > timezone float (min: -24) (max: 24) > > The person's current timezone offset from UTC > > > > token_for_business string > > A token that is the same across a business's apps. Access to this > token requires that the person be logged into your app. This token > will change if the business owning the app changes > > updated_time datetime > > Updated time > > shared_login_upgrade_required_by datetime > > The time that the shared loginneeds to be upgraded to Business Manager > by > > verified bool > > Indicates whether the account has been verified. This is distinct from > the is_verified field. Someone is considered verified if they take any > of the following actions: > > Register for mobile > Confirm their account via SMS > Enter a valid credit card > > video_upload_limits VideoUploadLimits > > Video upload limits > > viewer_can_send_gift bool > > Can the viewer send a gift to this person? > > website string > > The person's website > > work list > > Details of a person`s work experience > > public_key string > > The person's PGP public key > > cover CoverPhoto


Also, here's the current "Edge" stuff: The format for "Edge' stuff is this, roughly, I did this quickly:

"Edge"

"Description"

> favorite_requests > > Developers' favorite requests to the Graph API > > request_history > > Developers' Graph API request history > > accounts > > Facebook Pages this person administers/is an admin for > > achievements > > Achievements made in Facebook games > > adaccounts > > The advertising accounts to which this person has access > > adaccountgroups > > Ad account groups > > adcontracts > > The person's ad contracts > > admined_groups > > Groups the user admins > > adnetworkanalytics > > Insights data for the person's Audience Network apps > > albums > > The photo albums this person has created > > apprequests > > This person's pending requests from an app > > apprequestformerrecipients > > App requests > > books > > The books listed on this person's profile > > domains > > The domains the user admins > > events > > Events for this person. By default this does not include events the > person has declined or not replied to > > family > > This person's family relationships. > > stream_filters > > A list of filters that can be applied to the News Feed edge > > friendlists > > The person's custom friend lists > > ids_for_business > > Business entities can claim ownership of multiple apps using the > Business Manager. This edge returns the list of IDs that this user has > in any of those other apps > > invitable_friends > > A list of friends that can be invited to install a Facebook Canvas app > > games > > Games this person likes > > groups > > The Facebook Groups that the person belongs to > > likes > > All the Pages this person has liked > > movies > > Movies this person likes > > music > > Music this person likes > > objects > > Objects > > permissions > > The permissions that the person has granted this app > > photos > > Photos the person is tagged in or has uploaded > > picture > > The person's profile picture > > tagged_places > > List of tagged places for this person. It can include tags on videos, > posts, statuses or links > > promotable_domains > > All the domains user can promote > > promotable_events > > All the events which user can promote. > > taggable_friends > > Friends that can be tagged in content published via the Graph API > > television > > TV shows this person likes > > videos > > Videos the person is tagged in or uploaded > > video_broadcasts > > Video broadcasts from this person > > applications > > The Facebook apps that this person is a developer of. > > checkins > > The checkins this person has made. > > feed > > The feed of posts (including status updates) and links published by > this person. > > friendrequests > > A person's pending friend requests. > > friends > > A person's friends. > > home > > A person's Facebook homepage feed. > > inbox > > A person's Facebook Messages inbox. > > locations > > A feed of posts and photos that include location information and in > which this person has been tagged. This is useful for constructing a > chronology of places that the person has visited. > > mutualfriends > > The list of mutual friends between two people. > > notifications > > The unread Facebook notifications that a person has. > > outbox > > A person's Facebook Messages outbox. > > questions > > The questions that a person has created. > > scores > > The scores this person has received from Facebook Games that they've > played. > > subscribers > > The profiles that are following this person. > > subscribedto > > The profile that this person is following.

Solution 2 - Ios

use "fields" as Key and then comma separate your values

let params = ["fields": "email, friends"]

Solution 3 - Ios

In Obj-C insert in the logInWithReadPermissions method:

parameters:@{@"fields": @"id, name, email"}

if you leave nil in parameters you only receive id and name in the result object, although you have set for example:

NSArray *permissionsArray = @[ @"email", @"public_profile"];

It´s not very clear in the documentation, hope it can helps.

Solution 4 - Ios

I had the same problem, but adding field options would generate a request error when fetching the user photo. I solved this problem by adding a simple parameters:@{@"fields": @""} to the code:

FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:[NSString stringWithFormat:@"me/picture"]
                              parameters:@{@"fields": @""}
                              HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                      id result,
                                      NSError *error) {
    if (!error) {
        // success
    } else {
        // fail
    }}
];

Solution 5 - Ios

In Swift, you can declare multiple parameters like this:

let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "email, first_name, last_name, gender, picture"])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArminView Question on Stackoverflow
Solution 1 - IosLarry PicklesView Answer on Stackoverflow
Solution 2 - IosHugo PerezView Answer on Stackoverflow
Solution 3 - IosJosé Miguel GalvánView Answer on Stackoverflow
Solution 4 - IosPaula Vasconcelos GueirosView Answer on Stackoverflow
Solution 5 - IosdylankbuckleyView Answer on Stackoverflow