Upload Using AFNetworking - ios

NSURL *url = [NSURL URLWithString:#"http://127.0.0.1:8000/photo/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *headers = [NSDictionary dictionaryWithObject:data forKey:#"attachment"];
//NSLog(#"strimng");
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"upload/" parameters:nil constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) {
NSLog(#"strimng");
[formData appendPartWithFileData:data name:#"attachment" fileName:#"attachment.jpg" mimeType:#"image/jpeg"];
NSLog(#"strimng");
}];
NSLog(#"strimng");
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation start];
I am Trying to upload the image from the iphone using AFNetworking, but this is not working.
The NSLog just before formdata appenddata command is logged out. But the one after that doesnt seem to. I have also checked if NSdata is nil and thats also not the case. And obv the request is not being sent.
Please can anyone help me.

Assuming that you have to upload an image, why are you creating an NSDictionary with the data? It is not necessary, you just need to use data inside multipartFormRequestWithMethod.
Try the following
// Get the image that you want to upload via ImagePicker or a #property
UIImage *imageIWantToUpload = self.image;
// Create the NSData object for the upload process
NSData *dataToUpload = UIImageJPEGRepresentation(imageIWantToUpload, 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"upload/" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:dataToUpload name:#"attachment" fileName:#"attachment.jpg" mimeType:#"image/jpg"];
}];
// You can add then the progressBlock and the completionBlock
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:progress];
[operation setCompletionBlockWithSuccess:success failure:failure];
You should also double check if your server side expects some parameters, because you are setting the NSMutableURLRequest parameters' field to nil.

Related

How to upload hundreds of pictures by AFNetworking?

I would like to upload pictures, probably ranging from a few hundred to 1000, originally using AFNetwoking methods, but there is a drawback, it reads all image data one time, then memory is up,for example:
NSOperationQueue *operationQueue = [[NSOperationQueue alloc]init];
[operationQueue setMaxConcurrentOperationCount:1];
for (NSURL *fileURL in filesToUpload) {
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST"
URLString:#"http://example.com/upload" parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:fileURL name:#"images[]" error:nil];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operationQueue addOperation:operation];
}
this will read all pictures's data before upload, how can i create a queue reduced memory consumption

AFNetworking upload image with PUT request?

I'm trying upload image to server using AFNetworking with PUT request.-
UIImage* snap = info[UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(snap, 0.3);
NSMutableString * fullPath = [NSMutableString stringWithString:API_BASE_URL];
[fullPath appendFormat:#"%#%#",API_VERSION,req];
NSURL * url = [NSURL URLWithString:fullPath];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
[manager.requestSerializer setValue:[NSString stringWithFormat:#"%#", #kPublicKey] forHTTPHeaderField:#"X-API-KEY"];
[manager.requestSerializer setValue:bodyStr forHTTPHeaderField:#"X-API-DATA"];
NSString *URLString = fullPath;
NSMutableURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:#"PUT" URLString:URLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"media" fileName:#"upload.jpg" mimeType:#"image/jpeg"];
} error:nil];
AFHTTPRequestOperation *requestOperation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
//success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"failure...");
}];
[requestOperation start];
I'm taking image using iPhone camera and upload it to server but it takes too much time to process and images uploaded on server are in huge size(~10-12MB) although i'm trying to compress the image?
What i'm doing wrong?Any suggestion or sample code would be appreciated.
NSData *imageData = UIImageJPEGRepresentation(snap, 1.0);
The second argument in UIImageJPEGRepresentation denotes the compression quality of the image.As per Apple documentation :
compressionQuality :
The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality).
Try reducing this to a number which balances the quality of image and speed of upload.
// manager needs to be init'd with a valid baseURL
NSURL *baseURL = [AfarHTTPSessionManager sharedManager].baseURL;
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
NSData *imageData = UIImageJPEGRepresentation(draftHighlight.largeImage, 1);
// need to pass the full URLString instead of just a path like when using 'PUT' or 'POST' convenience methods
NSString *URLString = [NSString stringWithFormat:#"%#%#", baseURL, _the_rest_of_your_path];
NSMutableURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:#"PUT" URLString:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:kCreateHighlightAPIKeyImage fileName:#"highlight_image.jpg" mimeType:#"image/jpeg"];
}];
// 'PUT' and 'POST' convenience methods auto-run, but HTTPRequestOperationWithRequest just
// sets up the request. you're responsible for firing it.
AFHTTPRequestOperation *requestOperation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
// success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// failure
}];
// fire the request
[requestOperation start];

Can not upload video with multi part POST in AFNETWORKING on iOS

I tried below code to upload video with Multi part form POST in AFnetworking but when uploading, video sent about 80% is broken. This is my code:
-(void) uploadVideoAPI: (NSString*) emailStr andSumOfFiles: (NSString*) sumSizeFile andVideoNams:(NSMutableArray*) videoNameArr andUpFile :(NSMutableArray *) videoDataArray
{
NSURL *url = [NSURL URLWithString:#"http://myserver.com];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL: url] ;
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:nil parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData) {
[formData appendPartWithFormData:[emailStr dataUsingEncoding:NSUTF8StringEncoding]
name:#"emailStr"]; //parametters1
[formData appendPartWithFormData:[sumSizeFile dataUsingEncoding:NSUTF8StringEncoding] name:#"sumSizeFile"];//parametters 2
for(int i=0;i<[videoDataArray count];i++)
{
NSString * videoName = [videoNameArr objectAtIndex:i];
NSData *videoData = [videoDataArray objectAtIndex:i];
[formData appendPartWithFileData:videoData
name:#"videos"
fileName:videoName mimeType:#"video/quicktime"];
}
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Upload Complete");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", operation.responseString);
NSLog(#"%#",error);
}];
[operation start];
}
My code has any problem? Please give me some advice. thanks in advance
I suggest you to use appendPartWithFileURL instead of appendPartWithFormData for files, to avoid memory problems (imagine big data like video or compressed data files).
I use something like this:
// Create request
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:nil parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData) {
// Important!! : file path MUST BE real file path (so -> "file://localhost/.../../file.txt") so i use [NSURL fileURLWithPath:]
NSError* err;
[formData appendPartWithFileURL:[NSURL fileURLWithPath:filePathToUpload] name:[fileInfo objectForKey:#"fileName"] error:&err];
}];

Using AFNetworking to POST a file asynchronously with upload progress to Strava V3 API

I would like to post an activity to Strava from iOS.
Strava docs (http://strava.github.io/api/v3/uploads/#post-file) have curl example as following:
EXAMPLE REQUEST
$ curl -X POST https://www.strava.com/api/v3/uploads \
-F access_token=83ebeabdec09f6670863766f792ead24d61fe3f9 \
-F activity_type=ride \
-F file=#test.fit \
-F data_type=fit
In this case the file test.fit is the activity to post.
I am attempting to post this asynchronously using AFNetworking. I have the following test code:
NSURL *url = [NSURL URLWithString:#"https://www.strava.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *fileData = [NSData dataWithContentsOfFile:filename];
AFOAuthCredential *credential = [AFOAuthCredential retrieveCredentialWithIdentifier:kStravaTokenStored];
NSString *accessToken = credential.accessToken;
NSDictionary *parameters = #{#"access_token": accessToken, #"activity_type" : #"ride",#"data_type" : #"fit", #"name" : #"Test", #"stationary" : #"1" };
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"/api/v3/uploads" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:fileData name:#"Test" fileName:#"Test.fit" mimeType:#"application/octet-stream"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"succss %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"failure %# \n\n %#", error, operation);
}];
[httpClient enqueueHTTPRequestOperation:operation];
Currently I am seeing the following error:
Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code
in (200-299), got 400" UserInfo=0x9b62300
{NSLocalizedRecoverySuggestion={"message":"Bad
Request","errors":[{"resource":"Upload","field":"data","code":"empty"}]},
Anyone have an idea what I am missing here?
Thanks Ants
It has to be
[formData appendPartWithFileData:fileData name:#"file" fileName:#"Test.fit" mimeType:#"application/octet-stream"]
or not?

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!

Resources