AFNetworking upload a file referenced with a forKey - ios

I need to send to a web server some informations that the user inserts in my app
I was using ASIHTTPRequest but i'm having some problems with iOS 5, so I decided to move to AFNetworking
this is the code I've written so far...
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://theserver.com/upload.php"]];
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setObject:[fieldName text] forKey:#"name"];
[parameters setObject:[fieldSurname text] forKey:#"surname"];
Now I need to add a NSData object containing an image, and it should be referenced by forKey:#"attachment"
what should I write? with ASIHTTPRequest I was using
[request setData:myNSData withFileName:#"image.jpg" andContentType:#"application/octet-stream" forKey:#"attachment"];
but with AFNetworking I don't know what should I write, and the examples doesn't help me
thank you very much!

You need to use "multipartFormRequestWithMethod" - eg:
NSMutableURLRequest *request = [[AFHTTPClient sharedClient] multipartFormRequestWithMethod:#"POST" path:#"/upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:data mimeType:#"image/jpeg" name:#"attachment"];
}];

Related

How to make post request with AFnetworking?

I have to make a post request using AFNetworking library with following request parameters
{
"method":"validate",
"name":{
"firstname":"john",
"lastname":"doe"
}
}
How to make this request using latest version of AFNetworking v3 library?
I used the following code and it doesn't work
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
NSDictionary *parameters = #{\"method\":\"validate\",\"name\":{\"firstname\":\"john\",\"lastname\":\"doe\"}};
[manager POST:#"http://myUrl.." parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"%#",[responseObject description]);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"%#",[error localizedDescription]);
}];
Im getting the following error,
2016-02-13 11:04:54.085 SlideOutMenu[3698:50453] nulllllll
2016-02-13 11:04:55.794 SlideOutMenu[3698:50453] Failure Request failed: internal server error (500)
2016-02-13 11:04:55.795 SlideOutMenu[3698:50453] (null)
As you've already applied [manager setRequestSerializer:[AFJSONRequestSerializer serializer]] no need to convert dictionary to JSON again.
simply pass dictionary as a parameters, it will work.
NSDictionary *name = #{#"firstname": #"john", #"lastname": #"doe"};
NSMutableDictionary *parameters = [NSMutableDictionary new];
[parameters setObject:#"validate" forKey:#"method"];
[parameters setObject:name forKey:#"name"];
Also no need to initialise NSURLSessionConfiguration with defaultSessionConfiguration, AFNetworking will automatically initialise that. Simply use [AFHTTPSessionManager manager].
Your code is fine.Connect with your server guy.
code 500 is server side error.
check out this link for response code detail
http://www.restapitutorial.com/httpstatuscodes.html

Upload multiple images as file in iOS

In my iOS app I want to upload an image file and some other parameters through API. image file contains multiple images.
You can use custom image pickers like ELCImagePickerController
There is also some other library that can be used..
WSAssetPickerController
QBImagePickerController
These allow you to pick multiple images. let me know how things go
By Using AFNetworking You can upload multiple image as below code, download AFNetworking
Other Parameter :
NSDictionary *parametersAll = #{#"Value": #"Key"};
NSArray *imageArray;
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseUrl: my_url ];
NSMutableRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:nil
parameters:parametersAll constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
for(UIImage *img in imageArray)
{
[formData appendPartWithFileData: my_imageData name:#"image" fileName:#"myImage.jpg" mimeType:#"image/jpeg"];
}
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest: request];
[operation start];

Having trouble sending requests using AFNetWorking

It seems that AFNetworking isn't working correctly for me. Specifically when I send apiKey request to server it gives me an unauthorized error. ASIHTTPRequest works fine for me however, so there seems to be something I am doing wrong in AFNetWorking. I know the problem is sending apiKey because if I comment it out AFNetWork works correctly. I still need to send the API key however. Any help will be appreciated.
AFNetWorking
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:apiKey forHTTPHeaderField:#"apiKey"];
NSMutableDictionary *userinfo = [[NSMutableDictionary alloc] init];
[manager POST:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
[operation setUserInfo:userinfo];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[operation setUserInfo:userinfo];
}];
}
ASIHTTPRequest
NSString *urlStr = [NSString stringWithFormat:#"%#/%#", submitReportUrl, [self urlEncode:path]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
[request setDelegate:self];
NSMutableDictionary *userinfo = [[NSMutableDictionary alloc] init];
[userinfo setObject:NSStringFromSelector(self.didFinishSelector) forKey:#"didFinishSelector"];
[userinfo setObject:NSStringFromSelector(self.didFailSelector) forKey:#"didFailSelector"];
[request setUserInfo:userinfo];
[request addRequestHeader:#"apiKey" value:apiKey];
[request setRequestMethod:method];
NSArray *keys = [params allKeys];
for ( NSString *key in keys )
[request addPostValue:[params objectForKey:key] forKey:key];
[self.operationQueue addOperation:request];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
I had the same problem working with the post. So research where was the problem. If you did not add the about line of the code. AFNetworking will automatically add in the header
Content-Type : "text/html"
either one
Cotent-Type : "text/plain"
By adding above code becomes
Content-Type : "application/json"
So the problem is solved. Since the server is expecting JSON.

AFNetworking - Upload video along with other parameters

I want to upload video to web service along with some other parameters. I want to upload userID, videoID and video to web service. While uploading, all the parameters other than video is being sent to web service. I've checked at web service end, and the video is not coming with the request. I am using the following code.
- (void)uploadVideoAtLocalPath:(NSString *)videoPath videoID:(NSString *)videoID userID:(NSString *)userID {
NSString *strServerURL = #"www.mysite.com/user/uploadVideo";
NSURL *URL = [NSURL URLWithString:strServerURL];
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:URL];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
// userID
NSData *userIDData = [userID dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:userIDData name:#"userID"];
// videoID
NSData *videoIDData = [videoID dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:videoIDData name:#"videoID"];
// video
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:videoPath]];
[formData appendPartWithFileData:videoData name:#"video" fileName:#"video.mov" mimeType:#"video/quicktime"];
}];
[request setURL:URL];
[request setTimeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[AFHTTPRequestOperation addAcceptableStatusCodes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(100, 500)]];
[operation setCompletionBlockWithSuccess: ^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response String: %#", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
[client enqueueHTTPRequestOperation:operation];
}
Could anyone let me know whether I am doing it correct? If not, could anyone please tell me how to upload video to web service along with other parameters?
Thanks Everyone!
I'm not well in this method. I had the same issue. But, i have fixed it like mixing of POST & GET methods. I just sent my parameters as GET method like below -
NSString *strServerURL = [NSString stringWithFormat:#"www.mysite.com/user/uploadVideo&userID=%d&videoID=%d", 1, 55];
and, sent my video data in POST method as per your method -
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
// video
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:videoPath]];
[formData appendPartWithFileData:videoData name:#"video" fileName:#"video.mov" mimeType:#"video/quicktime"];
}];
You better try to modify your webservice and try like above way. It should works.
Cheers!

Always get "(#324) Requires upload file" when post image to Facebook with graph API

I always get "(#324) Requires upload file" when I post an image to facebook, there are many people asked the question with the same error, most of them are using php sdk, seems they solved the problem by set fileUpload to true ($facebook->setFileUploadSupport(true);), for example: http://endorkins.com/2010/12/28/facebook-graph-api-upload-photos-requires-upload-file/, Exception when uploading photo with Facebook Graph API
But I am using graph api directly in iOS, I can't find where to set this flag, I tried to set it when create the album and when upload the image, but it didn't work.
Facebook graph API reference (http://developers.facebook.com/docs/reference/api/album/) said can_upload must be true for an album to allow upload photos to the album, I checked the album that I tried to upload the image and it is true.
I also have permission of user_photos, friends_photos, publish_stream, publish_actions.
Below is my code to post the image, I have spent a lot of time on this but can't fix it, plz help me! any help is appreciated.
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:url];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:token forKey:#"access_token"];
[params setObject:#"the message" forKey:#"message"];
NSData *imgData = UIImageJPEGRepresentation(self.img, 1.0);
[params setObject:imgData forKey:#"source"];
NSMutableURLRequest *request = [client requestWithMethod:#"POST" path:[NSString stringWithFormat:#"%#/photos", albumId] parameters:params];
[request setValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
// [request setValue:[NSString stringWithFormat:#"%d", imgData.length] forHTTPHeaderField:#"Content-Length"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error);
NSLog(#"%#", operation.responseString);
}];
[operation start];
OK finally I solved this by using facebook SDK to post the image.

Resources