AFnetworking Cancel Specific Upload process - ios

I m uploading multiple image my images on server, URL is same for all.
Following is the code.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.securityPolicy.allowInvalidCertificates = YES;
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *parameters = #{KEY: VALUE};
NSString *imageUrl=[NSString stringWithFormat:#"%#/user/upload/item",BASE_SERVER_ADDRESS];
AFHTTPRequestOperation *op = [manager POST:imageUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSString *imageName = [NSString stringWithFormat:#"IMG00%i.png",count];
[formData appendPartWithFileData:_imageData name:#"files" fileName:imageName mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
double percentDone = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
//Upload Progress bar here
NSLog(#"progress updated(percentDone) : %f", percentDone);
}];
[op start];
I upload 10 images parallel and get the progress of each image individual. Now I want to cancel the specific uploading image, like 5th image.
How can I get the Operation of that image.
operationQueue has only NSOperation inside it. How will I know that specific NSOperation is the one I want to cancel.
Thanks.

You need to store operation you need to cancel in a variable, and later call [op cancel].

Related

access the web service and send data using iOS Objective C

I have string objects and image stored in nsdata. How can i send it to a server by accessing the url? I have seen examples .but its not working.Can someone tell me
Thanks in Advance!!
You could use AFNetworking to easily send string and image to server using url.
Here is a link of tutorial how to use AFNetworking framework.
AFNetworking Tutorial
AFNetworking is the best way to do that. and there are so much tutorials out there.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"username": _username.text,
#"password": passwordMD5
};
[manager POST:#"http://example.com/ws/test.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject); //This is the Response
}else{
//if you didnt get expected output then handle it here
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
//Handle any network errors here. ex: if internet disconnected.
}];
Here is an example how to upload an image with string objects as a dictionary to a server using AFNetworking.
- (void)uploadPhoto {
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://server.url"]];
NSData *imageData = UIImageJPEGRepresentation(self.avatarView.image, 0.5);
NSDictionary *parameters = #{#"username": self.username, #"password" : self.password};
AFHTTPRequestOperation *op = [manager POST:#"rest.of.url" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:imageData name:paramNameForImage fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
}

AFNetworking form data uploading issue

I want to POST form data using AFNetworking. I am using this piece of code to achieve this:
// Create service request url
NSString *urlString = [NSString stringWithFormat:#"%#%#", kBaseURL, webServiceAPIName];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:#"myUser" forHTTPHeaderField:#"X-User-Agent"];
[manager.requestSerializer setValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// Set calling keys
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:#"5341" forKey:#"Id"];
[dict setObject:#"f1" forKey:#"refDataId"];
[dict setObject:#"f1" forKey:#"customRefDataId"];
[dict setObject:#"587" forKey:#"cost"];
[manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation(files[0]) name:#"ImageName" fileName:#"file1" mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"upload successful");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error image upload");
}];
After execution of this block after waiting some time it goes in Failure Section. Logging : "Error image upload". without giving any error.
I tried my API in POSTMAN API CLIENT and there it is working fine.I am able to send data and get response back.
And after running this block i am not able to run any other API call I have to stop my app and run again to run any other API call.
What is the issue with this code why I am not able to upload any form data and Why it block my any other API calls
Try below code:
-(void) uploadImage {
NSString *imagePath = [[NSUserDefaults standardUserDefaults] objectForKey:#"userimage"];
NSString * urlString = [stagingURL stringByReplacingOccurrencesOfString:#"user/" withString:#""];
NSString * uploadURL = #"Your URL where image to be uploaded";
NSLog(#"uploadImageURL: %#", uploadURL);
NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]], 0.5);
NSString *queryStringss = [NSString stringWithFormat:#"%#",uploadURL];
queryStringss = [queryStringss stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/plain"];
[manager POST:queryStringss parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"file" fileName:#"file" mimeType:#"image/jpeg"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];}

Uploading image to server (Objective C)

I try to send image as byte[] to server.
When I sent it from POST-MAN, like html will send files, it works.
But when I try to send from Objective C code, it sents different array of bytes:
+ (void)uploadPhoto:(UIImage*)photo withCompletionBlock:(responceBlock)block
{
AFHTTPRequestOperationManager* manager = [[AFHTTPRequestOperationManager alloc] init];
NSData* imageData = UIImageJPEGRepresentation(photo, 6);
[manager.requestSerializer setValue:[UserDefaultsHelper getToken] forHTTPHeaderField:#"X-AUTH-TOKEN"];
AFHTTPRequestOperation* op = [manager POST:#"http://localhost:8080/image/save"
parameters:#{}
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"ParamFiles" fileName:#"photo2131231.jpg" mimeType:#"image/jpeg"];
}
success:^(AFHTTPRequestOperation* operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
}
failure:^(AFHTTPRequestOperation* operation, NSError* error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
}
Answer: Sorry for stupid question. Problem, that on server I handle just binary image. Objective C code send me multipart files, so it contains binary image with filename, mimetype and other fields. I converted everything to bytes and tried to save this like image. Of course server can't do that.
Try this out
+ (void)uploadPhoto:(UIImage*)photo withCompletionBlock:(responceBlock)block
{
AFHTTPRequestOperationManager* manager = [[AFHTTPRequestOperationManager alloc] init];
NSData* imageData = UIImageJPEGRepresentation(photo, 6);
[manager.requestSerializer setValue:[UserDefaultsHelper getToken] forHTTPHeaderField:#"X-AUTH-TOKEN"];
NSMutableURLRequest * request = [manager.requestSerializer
multipartFormRequestWithMethod:#"POST"
URLString:#"http://localhost:8080/image/save"
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
UIImage *image = [page.imageVersionObject imageForVersion:page.imageVersionObject.selectedVersion];
if (image) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, (CGFloat)0.85)
name:#"file"
fileName:#"fileName.jpg"
mimeType:#"image/jpeg"];
}
}
error:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//SUCCESS HERE!!!
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//FAILURE HERE
}];
[manager.operationQueue addOperation:operation];
}
Do not forget to use your filename and name.... I have used mine for testing

Image Posting is failing with Type Encoding Issue

I am trying to upload a picture from an iPhone to a Django Web Service and I keep getting a 400 with this specific message :
error: {"image": ["No file was submitted. Check the encoding type on the form."]}.
I have sat up for hours trying to figure this out and i believe that somehow, the mime-type is not being sent properly.
Would you have any ideas, or better ways to upload an image than my code below :
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://MYADDRESS"]];
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:#"user" password:#"pass"];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
NSDictionary *parameters = #{#"image" : imageData, #"name" : #"MyImage" , #"Content-Type" : #"image/jpeg"};
AFHTTPRequestOperation *op = [manager POST:#"/api/photo/" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"MyImage" fileName:#"MyImage.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"%f%% Uploaded", round(((float)totalBytesWritten / (float)totalBytesExpectedToWrite) * 100.));
}];
[op start];

AFNetworking 2.0 HTTP POST Progress

How can I get the progress of an AFHTTPRequest? I've tried searching all over the net.
I am using:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"gameId" : datas[0], #"p1": datas[1], #"p2":datas[2], #"turn":datas[3] };
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:#"http://localhost/thepath/isprivate/thefile.php"
parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Is there like, a property or method I can use to access the progress of an AFNetworking 2.0 HTTP POST?
Try this:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"gameId" : datas[0], #"p1": datas[1], #"p2":datas[2], #"turn":datas[3] };
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString:#"http://localhost/thepath/isprivate/thefile.php" parameters:params error:&error];
AFHTTPRequestOperation *requestOperation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"operation success: %#\n %#", operation, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[requestOperation setUploadProgressBlock:^(NSUInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
double percentDone = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
NSLog(#"progress updated(percentDone) : %f", percentDone);
}];
[requestOperation start];
Hope this helps.
The shortest way way to implement this is
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestOperation *requestOperation = [manager POST:#"/service/user/authenticate" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//Your Business Operation.
NSLog(#"operation success: %#\n %#", operation, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
//Here is the upload progress
[requestOperation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
double percentDone = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
//Upload Progress bar here
NSLog(#"progress updated(percentDone) : %f", percentDone);
}];
You can use following method
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromData:(NSData *)bodyData
progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
of AFHTTPSessionManager class.
UPDATE:
Usually you will prefer to use KVO to get uploading values. So something like following should be used:
static void * kDGProgressChanged = &kDGProgressChanged;
...
[progress addObserver:self
forKeyPath:#"fractionCompleted"
options:NSKeyValueObservingOptionNew
context:kDGProgressChanged];
...
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(__unused NSDictionary *)change
context:(void *)context
{
if (kDGProgressChanged == context) {
dispatch_async(dispatch_get_main_queue(), ^{
[self updateProgressInfo];
});
}
}

Resources