I am using the code bellow to get the list of all of users friends and check how many of them have installed the app so i can show their scores, and unlock some content for the user.
I can't find solid info about the field installed which seams to be perfect for this case.(If it specifies the user has installed the app which made the request :) )
[FBRequestConnection startWithGraphPath:#"me/friends"
parameters: #{ #"fields" : #"id,installed"}
HTTPMethod:nil
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (!error) {
// Get the result
NSArray *resultData = result[#"data"];
// Check we have data
if ([resultData count] > 0) {
// Loop through the friends returned
for (NSDictionary *friendObject in resultData) {
// Check if devices info available
if (friendObject[#"installed"]) {
//Do some work if user has installed my game
}
}
}
}
}];
-(void)FBFriendList
{
if (!FBSession.activeSession.isOpen)
{
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState state, NSError *error)
{
if (error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else if(session.isOpen)
{
[self FB_Common_Friend];
}
}];
return;
}
}
-(void)FB_Common_Friend
{
FBRequest *request = [FBRequest requestWithGraphPath:#"me/friends" parameters:#{#"fields":#"name,installed,first_name,picture"} HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
NSLog(#"%#",result);
int count = 0;
NSMutableArray *frnd_arr = [result objectForKey:#"data"];
for (int i = 0; i < [frnd_arr count]; i++)
{
if([[[frnd_arr objectAtIndex:i] objectForKey:#"installed"] boolValue])
{
count++;
}
}
app.fb_frnd_count = count;
}];
}
Related
I'm trying to get email from my logged in user using Facebook SDK. Here are 2 of my login methods
-(void)loginButtonClicked {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions: #[#"public_profile", #"email", #"user_friends"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(#"Process error");
} else if (result.isCancelled) {
NSLog(#"Cancelled");
} else {
[self getFBUSerData];
NSLog(#"Logged in");
}
}];
}
- (void) getFBUSerData {
if (FBSDKAccessToken.currentAccessToken != nil) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%# and Email : %#", result,result[#"email"]);
}
}];
}
}
The result in the log:
(lldb) po result
{
id = 42357***4506554;
name = "Fname Lname";
}
But no email or friends list. Any help how to get those?
You have to assign the parameters you need to get in getFBUserData().
Something like this:
- (void) getFBUSerData {
if (FBSDKAccessToken.currentAccessToken != nil) {
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:#[#"id, name, first_name, last_name, picture.type(large), email"] forKeys:#[#"fields"]];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:dict]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%# and Email : %#", result,result[#"email"]);
}
}]; }
}
Hi i am using ios8 for facebook sharing an image from iphone application to facebook and when i tapped photo button i am getting this error"The operation couldn’t be completed. (com.facebook.sdk error 8.)
this is the code i used to share an image from iphone application to facebook .
- (IBAction)photo:(id)sender
{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
// Process error
}
else if (result.isCancelled)
{
// Handle cancellations
}
else
{
if ([result.grantedPermissions containsObject:#"email"])
{
//NSLog(#"result is:%#",result);
[self photo];
}
}
}];
}
- (void)photo
{
FBSDKAccessToken *token = [FBSDKAccessToken currentAccessToken];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
UIImage *image = [UIImage imageNamed:#"TEST.png"];
NSDictionary *parameters = #{
#"message" : #"welcome",
#"picture" : UIImagePNGRepresentation(image),
};
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me/photos" parameters:parameters tokenString:token.tokenString version:#"nil" HTTPMethod:#"POST"];
[connection addRequest:request completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(error)
NSLog(#"%#", error);
else
NSLog(#"Success");
}];
[connection start];
}
This is the error i am getting
fb sharing[1065:90399] Error Domain=com.facebook.sdk.core Code=8 "The operation couldn’t be completed. (com.facebook.sdk.core error 8.)" UserInfo=0x155c7720 {com.facebook.sdk:FBSDKGraphRequestErrorGraphErrorCode=2500, com.facebook.sdk:FBSDKGraphRequestErrorParsedJSONResponseKey={
body = {
error = {
code = 2500;
"fbtrace_id" = ErePY87sZ34;
message = "Unknown path components: /me/photos";
type = OAuthException;
};
};
code = 400;
}, com.facebook.sdk:FBSDKGraphRequestErrorHTTPStatusCodeKey=400, com.facebook.sdk:FBSDKErrorDeveloperMessageKey=Unknown path components: /me/photos, com.facebook.sdk:FBSDKGraphRequestErrorCategoryKey=0}
Any help is appreciated.
I am making a call to twitters API to load some tweets for a specific section of my app.
A small chunk of users are reporting a crash when loading the tweets view, while the rest have no problem at all.
I have submitted the code to Apple Tech Support and they responded letting me know that NSJSONSerialization can sometimes return a NSArray or NSDictionary.
Obviously it will throw an error is objectAtIndex: is called on an NSDictionary object, which I believe is the culprit for all of my users.
The partial solution is to detect if it is an Array or NSDictionary.
Here is where I am at now:
id feedData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonError];
if ([feedData isKindOfClass:[NSArray class]]) {
//Is array
} else if ([feedData isKindOfClass:[NSDictionary class]]) {
//is dictionary
}
I basically need an NSArray every single time. So in the is array block, I basically just use the feedData, but in NSDictionary, how can I convert it to an NSArray that will match the structure I need.
Honestly the biggest issue is that I cannot see what the NSDictionary structure looks like because none of my testing devices or simulator return the NSDictionary data, they all return an NSArray.
Here is what the entire getUserFeed method that sends the request to twitter looks like:
// Get the twitter feed
NSURL *requestURL = [NSURL URLWithString:TW_API_TIMELINE];
// Set up proper parameters
NSMutableDictionary *timelineParameters = [[NSMutableDictionary alloc] init];
[timelineParameters setObject:kNumTweets forKey:#"count"];
[timelineParameters setObject:#"1" forKey:#"include_entities"];
// Create the Social Request
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:requestURL parameters:timelineParameters];
postRequest.account = self.delegate.userAccount;
// Perform the request
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
// Check if we reached the reate limit
if ([urlResponse statusCode] == 429) {
// Rate limit reached
// Display an alert letting the user know we have hit the rate limit
UIAlertView *twitterAlert = [[UIAlertView alloc] initWithTitle:kRateLimitTitle
message:kRateLimitMessage
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[twitterAlert show];
// Stop animating the pull to refresh if it is animating
[self.feedTableView.pullToRefreshView stopAnimating];
return;
}
// Check if there was an error
if (error) {
NSLog(#"Error: %#", error.localizedDescription);
// Stop animating the pull to refresh if it is animating
[self.feedTableView.pullToRefreshView stopAnimating];
return;
}
// Check if there is some response data
if (responseData) {
NSError *jsonError = nil;
id feedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&jsonError];
if ([feedData isKindOfClass:[NSArray class]]) {
//Is array
NSLog(#"It's an Array");
} else if ([feedData isKindOfClass:[NSDictionary class]]) {
//Is dictionary
NSLog(#"It's a Dictionary");
} else {
//is something else
}
if (!jsonError) {
[self gatherTweetsFromArray:feedData];
} else {
// Stop animating the pull to refresh if it is animating
[self.feedTableView.pullToRefreshView stopAnimating];
// Alert the user with the error
UIAlertView *twitterAlert = [[UIAlertView alloc] initWithTitle:kErrorTitle
message:kErrorMessage
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[twitterAlert show];
}
} else {
// Stop animating the pull to refresh if it is animating
[self.feedTableView.pullToRefreshView stopAnimating];
// Alert the user with the error
UIAlertView *twitterAlert = [[UIAlertView alloc] initWithTitle:kErrorTitle
message:kErrorMessage
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[twitterAlert show];
}
});
}];
This is a MAJOR bug and I need to squash it, so any ideas or information will be greatly appreciated! Thank you!
When I run [_accountStore requestAccessToAccountsWithType: ...] I am getting no response. My completion handler isn't being called. However I do have access to twitter.
// Step 0: Check that the user has local Twitter accounts
if ([SLComposeViewController
isAvailableForServiceType:SLServiceTypeTwitter]) {
NSLog(#"OH YES!!!");
// Step 1: Obtain access to the user's Twitter accounts
ACAccountType *twitterAccountType = [_accountStore accountTypeWithAccountTypeIdentifier: ACAccountTypeIdentifierTwitter];
NSLog(#"OH YES!!!");
[_accountStore requestAccessToAccountsWithType:twitterAccountType options:nil
completion:^(BOOL granted, NSError *error)
{
NSLog(#"Im in!");
if (granted == YES)
{
NSArray *arrayOfAccounts = [_accountStore
accountsWithAccountType:twitterAccountType];
if ([arrayOfAccounts count] > 0)
{
ACAccount *twitterAccount = [arrayOfAccounts lastObject];
NSLog(#"%#", twitterAccount.userFullName);
NSLog(#"%#", twitterAccount.username);
NSLog(#"%#", twitterAccount.credential);
NSLog(#"%#", twitterAccount.identifier);
}
}else{
NSLog(#"Failed muahahaha");
}
}];
}
Why is this happening?
Make shure _accountStore is initialized for example with
_accountStore = [[ACAccountStore alloc] init];
I'm trying to detect how many invites the user has sent while logged into their Facebook account. For example, I'm giving the user an option to purchase an item by inviting 3 friends to use the iOS application. If they invite 3, they are rewarded with the item. I'm really stuck on this one. Any help would be great and much appreciated!
I actually found code snippet for this after much research. I can't remember if it was on here or not, but here it is.
- (IBAction)inviteFacebookFriendsButton:(id)sender
{
// FBSample logic
// if the session is open, then load the data for our view controller
if (!FBSession.activeSession.isOpen)
{
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:NO
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
} else if (session.isOpen) {
}
}];
}
MouseInTheHouseAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
if (appDelegate.session.isOpen)
{
NSMutableDictionary *postVariablesDictionary = [[NSMutableDictionary alloc] init];
[postVariablesDictionary setObject:#"Come play Mouse in the House with me!" forKey:#"message"];
[postVariablesDictionary setObject:#"Invite Friends" forKey:#"title"];
[FBWebDialogs presentDialogModallyWithSession:[FBSession activeSession] dialog:#"apprequests" parameters:postVariablesDictionary handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
{
if (error)
{
// Case A: Error launching the dialog or sending request.
NSLog(#"Error sending request.");
}
else
{
if (result == FBWebDialogResultDialogNotCompleted)
{
// Case B: User clicked the "x" icon
NSLog(#"User canceled request.");
}
else
{
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:#"to%5B\\d+%5D=(\\d+)"
options:NSRegularExpressionCaseInsensitive
error:NULL];
NSArray * matches = [regex matchesInString:resultURL.absoluteString
options:0
range:(NSRange){0, resultURL.absoluteString.length}];
NSMutableArray * ids = [NSMutableArray arrayWithCapacity:matches.count];
for (NSTextCheckingResult * match in matches)
{
[ids addObject:[resultURL.absoluteString substringWithRange:[match rangeAtIndex:1]]];
}
NSLog(#"Number of friends invited: %lu", (unsigned long)ids.count);
}
}
}];
}
}