Can't load facebook profile image - objective-c

I have a problem with uploading profile picture from facebook to my API and saving to Parse. This code is from Udemy. I'm using Xcode 7.2.
Error:
2016-01-18 10:14:15.296 MatchedUp[14381:5418567] Error in FB request Error Domain=com.facebook.sdk Code=5 "(null)" UserInfo={com.facebook.sdk:HTTPStatusCode=400, com.facebook.sdk:ErrorSessionKey=<PFReceptionist: 0x12663d2e0>, com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 100;
"fbtrace_id" = "FXTRrxOh0+c";
message = "(#100) Tried accessing nonexisting field (photo) on node type (User)";
type = OAuthException;
};
};
code = 400;
}}
Code:
-(void)updateUserInformation
{
//
FBRequest *request = [FBRequest requestForGraphPath:#"me/?fields=name,birthday,first_name,location,gender,interested_in,photo"];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error){
NSDictionary *userDictionary = (NSDictionary *)result;
//create URL
NSString *facebookID = userDictionary[#"id"];
NSLog(#"%#",result);
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
NSData *imageData = [NSData dataWithContentsOfURL:pictureURL];
// UIImage *fbImage = [UIImage imageWithData:imageData];
NSLog(#"%#",result);
NSMutableDictionary *userProfile = [[NSMutableDictionary alloc] initWithCapacity:8];
NSLog(#"%#",result);
if(userDictionary[#"name"]){
userProfile[kCCUserProfileNameKey] = userDictionary[#"name"];
}
if(userDictionary[#"user_birthday"]){
userProfile[kCCUserProfileBirthdayKey] = userDictionary[#"user_birthday"];
}
if(userDictionary[#"first_name"]){
userProfile[kCCUserProfileFirstNameKey] = userDictionary[#"first_name"];
}
if(userDictionary[#"location"][#"name"]){
userProfile[kCCUserProfileLocationNameKey] = userDictionary[#"location"][#"name"];
}
if(userDictionary[#"gender"]){
userProfile[kCCUserProfileGenderKey] = userDictionary[#"gender"];
}
if(userDictionary[#"interested_in"]){
userProfile[kCCUserProfileInterestedInKey] = userDictionary[#"interested_in"];
}
if([pictureURL absoluteString]){
userProfile[kCCUserProfilePictureURL] = [pictureURL absoluteString];
}
[[PFUser currentUser] setObject: userProfile forKey:kCCUserProfileKey];
[[PFUser currentUser] saveInBackground];
[self requestImage];
}
else{
NSLog(#"Error in FB request %#", error);
}
}];
}
-(void) uploadPFFileToParse:(UIImage *)image
{
NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
if(!imageData){
NSLog(#"imageData was not found");
return;
}
PFFile *photoFile = [PFFile fileWithData:imageData];
[photoFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
if(succeeded){
PFObject *photo = [PFObject objectWithClassName:kCCPhotoClassKey];
[photo setObject:[PFUser currentUser] forKey:kCCPhotoUserKey];
[photo setObject:photoFile forKey:kCCPhotoPictureKey];
[photo saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
NSLog(#"Photo saved successfully");
}];
}
}];
}
-(void) requestImage
{
PFQuery *query = [PFQuery queryWithClassName:kCCPhotoClassKey];
[query whereKey:kCCPhotoUserKey equalTo:[PFUser currentUser]];
[query countObjectsInBackgroundWithBlock:^(int number, NSError * _Nullable error) {
if(number == 0 )
{
PFUser *user = [PFUser currentUser];
self.imageData = [[NSMutableData alloc] init];
NSURL *profilePictureUrl = [NSURL URLWithString:user [kCCUserProfileKey][kCCUserProfilePictureURL]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:profilePictureUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:4.0f];
NSURLConnection *urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];
if(!urlConnection){
NSLog(#"Failed to Download Picture");
}
}
}];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.imageData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
UIImage *profileImage = [UIImage imageWithData:self.imageData];
[self uploadPFFileToParse:profileImage];
}
#end
Any idea how can i fix this problem?
Thanks a lot!

Try this.
- (void)getFBProfilePicture {
NSString *facebookId = #"yourFacebookId";
NSString *imageUrl = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookId];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = [UIImage imageWithData:imageData];
});
});
}

Related

Pause/Resume download with AFNetworking 3.0 and NSURLSessionDownloadTask Objective-C, OSX

I have trouble with creating Pause/Resume download methods in my Objective-C osx app, I have tried some of the answers I found here but nothing seems to work.
Here is my code: `-(void)pauseDownload:(id)sender {
if(!downloadTask) return;
[downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
if (!resumeData) return;
[self setDownloadResumeData:resumeData];
[self setDownloadTask:nil];
}];
NSString *datastring = [[NSString alloc] initWithData:downloadResumeData encoding:NSUTF8StringEncoding];
isDownloading = NO;
NSLog(#"data %#", datastring);}`
Continue method:
-(void)continueDownload:(id)sender {
if (!self.downloadResumeData) {
return;
}
self.downloadTask = [manager.session downloadTaskWithResumeData:self.downloadResumeData];
[self.downloadTask resume];
[self setDownloadResumeData:nil];}
And download request with download task:
-(void)downloadRequest:(NSString *)url toDirectory:(NSString *)directoryName atIndex:(NSInteger) rowIndex {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSString *downloadDirectoryPath = [[NSUserDefaults standardUserDefaults] objectForKey:#"downloadPath"];
NSURL *downloadURL;
if (directoryName != nil || ![directoryName isEqualToString:#""]) {
downloadURL = [self createDownloadDirectoryIn:downloadDirectoryPath withName:directoryName];
} else {
downloadURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:#"downloadFolderPath"]];
}
downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(#"%#", downloadProgress);
// [self downloadStartedWithDownloadId:downloadID andDeviceId:userDeviceID];
isDownloading = YES;
NSNumber *downloadPercentage = [NSNumber numberWithInteger:downloadProgress.fractionCompleted *100];
progressArray[rowIndex] = downloadPercentage;
[self updateProgressBars];
} destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
return [downloadURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
[[files objectAtIndex:self.tableOfContents.selectedRow] setIsFinishedDownloading:YES];
// [self downloadFinishedWithDownloadID:downloadID andDeviceID:userDeviceID];
NSLog(#"File downloaded to: %#", filePath);
}] ;
[downloadTask resume];}
Appreciate any help.

iOS - Downloading Video Data from Parse

I am trying to download a PFFile which is a tfss file(?). It gets opened as a text file. This is the code I use for retrieveing the data:
-(void) queryVideoWithDictionary:(NSDictionary *)dictionary {
PFQuery *videoQuery = [PFQuery queryWithClassName:#"EventVideos"];
[videoQuery whereKey:#"objectId" equalTo:[dictionary objectForKey:#"videoId"]];
[videoQuery findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
if (!error) {
PFFile *videoFile = [results[0] objectForKey:#"video"];
[videoFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSURL *movieURL = [NSURL fileURLWithPath:dataString];
NSMutableDictionary *videoDictionary = [NSMutableDictionary dictionaryWithObject:data forKey:[dictionary objectForKey:#"videoId"]];
[self.videoArray addObject:videoDictionary];
NSLog(#"video array count: %ld", self.videoArray.count);
NSLog(#"dataString: %#", dataString);
// NSLog(#"movieURL: %#", movieURL);
[self.player setItemByStringPath:dataString];
[self.player play];
});
}];
} else {
NSLog(#"error");
}
}];
}
When dataString gets logged, it returns null, so I don't know how to get the data and play it as a video. It is saved as a QuickTimeMovie by the way.
I use SCRecorder to play and record videos.
Edit: data is definitely not nil, I still don't know how to solve this issue.

Fetch only MyContacts from gmail account in iOS

I am trying to fetch gmail & yahoo contacts in my iPhone application.
For Gmail I have used GTMOauth2.0. I can see all contacts but when I want only contacts from MyContacts group. I have used following code to get contacts:
-(void)signInToGoogle:(id)sender
{
[self signOutFromGoogle];
NSString *keychainItemName = nil;
NSString *scope = #"https://www.google.com/m8/feeds/contacts/default/full";
NSString *clientID = #"CLIENTID";
NSString *clientSecret = #"CLIENTSECRETID";
SEL finishedSel = #selector(viewController:finishedWithAuth:error:);
GTMOAuth2ViewControllerTouch *viewController;
viewController = [GTMOAuth2ViewControllerTouch controllerWithScope:scope
clientID:clientID
clientSecret:clientSecret
keychainItemName:keychainItemName
delegate:self
finishedSelector:finishedSel];
NSDictionary *params = [NSDictionary dictionaryWithObject:#"en" forKey:#"hl"];
viewController.signIn.additionalAuthorizationParameters = params;
NSString *html = #"<html><body bgcolor=silver><div align=center>Loading sign-in page...</div></body></html>";
viewController.initialHTMLString = html;
[[self navigationController] pushViewController:viewController animated:YES];
}
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (error != nil) {
[processObj removeFromSuperview];
self.view.userInteractionEnabled = YES;
NSLog(#"Authentication error: %#", error);
NSData *responseData = [[error userInfo] objectForKey:#"data"]; // kGTMHTTPFetcherStatusDataKey
if ([responseData length] > 0) {
// show the body of the server's authentication failure response
NSString *str = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSLog(#"%#", str);
}
self.auth = nil;
} else {
self.auth = auth;
[self doAnAuthenticatedAPIFetch];
}
}
- (void)doAnAuthenticatedAPIFetch {
NSString *urlStr = #"https://www.google.com/m8/feeds/groups/default/full/Contacts";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[self.auth authorizeRequest:request
completionHandler:^(NSError *error) {
NSString *output = nil;
if (error) {
output = [error description];
} else {
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (data) {
// API fetch succeeded :Here I am getti
output = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
} else {
// fetch failed
output = [error description];
}
}
}];
}
In the API I am passing "Contacts" as a group id but it is returning error "Group Id Not Found". I have the google document from
https://developers.google.com/google-apps/contacts/v3/?csw=1
but still can't solve the problem. Help me on these.
You'll need to fetch the groups feed to get the ID for a group. See the groups feed documentation, or try the ContactsSample app provided with the Google Data APIs Objective-C Client Library.

how to change my synchronous to asynchronous call in Objective-C?

hi friend i am beginner for objective-c.i have slow response from server side due to synchronous call. i analysed in google the call may be asynchronous means the response speed will be high, but i don't know much about NSURLConnection and GCD. so please help me how to change my call asynchronous . see my code below`
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString* oldToken = [self deviceToken];
NSString *newToken = [[[[deviceToken description]stringByReplacingOccurrencesOfString:#"<"withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"My token is: %#", newToken);
[self setDeviceToken:newToken];
if (![newToken isEqualToString:oldToken])
{
[self calur:newToken];
}
}
- (NSString*)deviceToken{
return [[NSUserDefaults standardUserDefaults] stringForKey:#"deviceid"];
}
- (void)setDeviceToken:(NSString*)token{
[[NSUserDefaults standardUserDefaults] setObject:token forKey:#"deviceid"];
}
//This function used to store a notification device id to our notification databae
-(void)calur:(NSString *)device
{
NSString *post =[NSString stringWithFormat:#"deviceId=%#",device];
NSString *hostStr = #"https://myserver.com/Ver_2_0/notification/check.php?";
NSError *error = nil;
NSString *nocon=[NSString stringWithContentsOfURL:[NSURL URLWithString:hostStr]encoding:NSUTF8StringEncoding error:&error];
if (nocon == nil)
{
NSLog(#"NO Connection");
}
else
{
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"hostStr=%#",hostStr);
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"dataURL=%#",dataURL);
// NSData *dataurl=dataURL;
if([serverOutput isEqualToString:#"Token Updated Successfully"])
{
NSLog(#"badge updated");
}
else
{
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"not registered");
}
[serverOutput release];
}
}`
if (nocon == nil)
{
NSLog(#"NO Connection");
}
else
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"hostStr=%#",hostStr);
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"dataURL=%#",dataURL);
// NSData *dataurl=dataURL;
if([serverOutput isEqualToString:#"Token Updated Successfully"])
{
NSLog(#"badge updated");
}
else
{
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"not registered");
}
[serverOutput release];
});
}
a little snippet:
#import "AFNetworking.h"
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:self.value, #"POSTvar", nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: [NSURL URLWithString:#"http://your.address"]];
NSURLRequest *request = [client requestWithMethod:#"POST" path:nil parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// do some with JSON
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
});
AFNetworking github

Facebook in iOS6.0 use SLRequest to upload a photo failed anyway

Here Comes my Objc code:
ACAccountStore *facebookaccount = [[ACAccountStore alloc] init];
ACAccountType *facebookaccountType = [facebookaccount accountTypeWithAccountTypeIdentifier: ACAccountTypeIdentifierFacebook];
// Specify App ID and permissions
NSDictionary *options = #{ ACFacebookAppIdKey: #"1234567899876543", ACFacebookPermissionsKey: #[#"publish_stream"], ACFacebookAudienceKey: ACFacebookAudienceFriends };
[facebookaccount requestAccessToAccountsWithType:facebookaccountType options:options completion:^(BOOL granted, NSError *error) {
if(granted) {
NSArray *accountsArray = [facebookaccount accountsWithAccountType:facebookaccountType];
if ([accountsArray count] > 0) {
ACAccount *facebookAccount = [accountsArray objectAtIndex:0];
NSString *sendmessage = #"Face";
NSData *myImageData = UIImagePNGRepresentation(imageSource);
SLRequest *facebookRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"https://graph.facebook.com/me/photos"] parameters:nil];
[facebookRequest addMultipartData:myImageData withName:#"source" type:#"multipart/form-data" filename:nil];
[facebookRequest addMultipartData:[sendmessage dataUsingEncoding:NSUTF8StringEncoding] withName:#"message" type:#"multipart/form-data" filename:nil];
[facebookRequest setAccount:facebookAccount];
[facebookRequest performRequestWithHandler:^(NSData* responseData, NSHTTPURLResponse* urlResponse, NSError* error) {
if (error == nil) {
NSLog(#"responedata:%#", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
}else{
NSLog(#"%#",error.description);
}
}
}
else
{
NSLog(#"error description : %#",[NSString stringWithFormat:#"%#", error.localizedDescription]);
}
}];
Finally I get these respone data:
responedata:{"error":{"message":"(#324) Requires upload file","type":"OAuthException","code":324}}
Help me please!!!
I can successfully upload a photo by including a file name in addMultipartData and by passing the message as part of the SLRequest options.
code:
NSDictionary *parameters = #{#"message": sendmessage};
SLRequest *facebookRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:[NSURL URLWithString:#"https://graph.facebook.com/me/photos"]
parameters:parameters];
[facebookRequest addMultipartData: myImageData
withName:#"source"
type:#"multipart/form-data"
filename:#"TestImage"];
facebookRequest.account = facebookAccount;
[facebookRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
// Log the result
}];