In my app have an array of dictionaries containing GPS logs (100 per dictionary). I have to post these dictionaries one at a time to a server. The problem I am having is not posting which works just wonderful with RestKit, it is that I have to post them in the same order as they are in the array. This is due to an index count in the dictionaries which shouldn't be messed up on the server and in the same order as in the array.
How can I post these objects using RestKit in a synchronous manner?
Here ist the code I am using currently (asynchronous):
for (int i = 0; i < [arrayOfGPSLogChunks count]; i++)
{
NSMutableDictionary *historyToUpload = [[NSMutableDictionary alloc] init];
[historyToUpload setObject:driveID forKey:#"driveID"];
[historyToUpload setObject:[arrayOfGPSLogChunks objectAtIndex:i] forKey:#"gpsLog"];
[[RKObjectManager sharedManager] postObject:nil
path:#"api/drives/addDriveChunk"
parameters:historyToUpload
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult)
{
RKLogInfo(#"Successfully Uploaded Drive Chunk %i/%i", i,arrayOfGPSLogChunks.count);
}
failure:^(RKObjectRequestOperation *operation, NSError *error)
{
RKLogError(#"Failed Uploading Drive Chunk (%i): (Error: %#)", i, error);
}];
}
Update:
I tried using this method which does work just the ways I want it to but it blocks my whole UI thread:
for (int i = 0; i < [arrayOfGPSLogChunks count]; i++)
{
NSMutableDictionary *historyToUpload = [[NSMutableDictionary alloc] init];
[historyToUpload setObject:driveID forKey:#"driveID"];
[historyToUpload setObject:[arrayOfGPSLogChunks objectAtIndex:i] forKey:#"gpsLog"];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:historyToUpload options:NSJSONWritingPrettyPrinted error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:kUploadDrivesChunkURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kConnectionTimeOut];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
RKObjectRequestOperation *operation = [[RKObjectManager sharedManager] objectRequestOperationWithRequest:request success:nil failure:nil];
[operation start];
[operation waitUntilFinished];
if (operation.error)
{
...
}
}
Thanks a lot!
You should use NSOperationQueue to manage your server calls and setMaxConcurrentOperationCount to 1, like:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue setMaxConcurrentOperationCount:1];
You can also take a look at this Link for further details.
You can set the operation queue of the object managers http client to have a max concurrent count of 1. Of you can use RestKit to do the mapping and then use something else to upload.
Arguably you should modify the server so that you send the objects and associated ordering information and then it doesn't matter what order they are received in (and this will remove numerous likely headaches in the future).
Related
I am new in operation queue, so give me flexibility to ask that question which may ask already meanwhile I searched a lot but not able to find my desired solution.
I have a API which delete single document and its working fine via using AFNetworking(which take documentID as param and accesstoken). Now I want to delete multiples document the solution should be that I should have another API which takes array or string (comma separated).
As far as I know the solution should be to call that API into Loop and delete all, but I heard another solution which is NSOperationQueue. I saw tutorial but I am not able to use those in right manner.
Here below is my code to call one operation.
NSString *jsonString = #"";
NSString *authorizationValue = [self setAuthorizationValue:action];
NSString *language = #"en_US";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:language forHTTPHeaderField:#"Accept-Language"];
[request setValue:authorizationValue forHTTPHeaderField:#"authorization"];
//convert parameters in to json data
if ([params isKindOfClass:[NSDictionary class]]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
[request setURL:[NSURL URLWithString:action]];
[request setTimeoutInterval:500.0];
[request setHTTPMethod:#"DELETE"];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
So kindly guide me how call this in operation queue, do I need to create these call and put into array and then add those into operation queue.
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
// Set the max number of concurrent operations (threads)
[operationQueue setMaxConcurrentOperationCount:3];
[operationQueue addOperations:#[operation] waitUntilFinished:NO];
Looking for your response.
Thanks
the solution should be that I should have another API which takes array or string (comma separated)
This would be the best solution, yes, because it minimise the workload of the client and the server and makes the smallest number of network requests possible - it's fast and efficient.
the solution should be to call that API into Loop and delete all, but I heard another solution which is NSOperationQueue
Using an operation queue is better than running in a loop because you have control over the timing (how many operations run concurrently), which you already show in your code.
The only issue with your code is calling NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init]; each time before adding the new operation. Instead of doing that you should create and configure the operation queue once and store a strong reference to it. Otherwise you have lots of different operation queues each executing operations concurrently and your setting of setMaxConcurrentOperationCount:3 means nothing.
Im trying to send some json data to a http server in my ios app, but I dont know how to verify if data got there... For testing Im using http://www.jsontest.com/.
NSURL *url = [NSURL URLWithString:#"http://validate.jsontest.com"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:createJson()]; //createJson() is my function which pass json data
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://validate.jsontest.com"]]; //by this I want to open json site in browser and see if data come. - but something different should be here I guess
So... How should I change my code to see data from createJson() in browser? Are there any mistakes in code so data arent even sent to a server?
Thank you for any help.
I recommend using AFNetworking
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
That you have 2 blocks one runs on success & other on failure.
This is the link on Github
https://github.com/AFNetworking/AFNetworking
I'm looping through an array which contains few strings and making a request to a web server for each
strings in the array.
I would like each request to be processed completely before the subsequent request is sent to the server. Because each request sends me a response which I will send with next request and so on.
The problem I am having is that my NSURLConnection is set up using the standard asynchronous call. This results in requests not blocking any subsequent requests. But I need to block other requests in the loop before first completes.
The request URL is same always , only JSON data changes with every request in the loop.
Here is my code
for (int i = 0; i < array.count; i++)
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:finalJSON options:NSJSONWritingPrettyPrinted error:&error];
if (!jsonData) {
NSLog(#"Error creating JSON object: %#", [error localizedDescription]);
}
NSString *url = [NSString stringWithFormat:#“abc.com/folders”];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"application/json;charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:APIKEY forHTTPHeaderField:#"X_API_KEY"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
//I am adding all connections to NSDictionary so that later I can process request.
NSURLConnection *connection = [self connectionForRequest:request];
[connection start];
}
I thought of 2 solutions for your problem:
AFNetworking - U can use AFNetworking and maintain a counter in the success block. The counter will count the requests and when all done, will do your next task.
GCD - Dispatch Groups - Grand Central Dispatch provide u the option to make group or requests and do something at the end (when all the requests finished). For that, u need to read nice tutorial (2nd part of "Ray Wenderlich". If U r not familiar with GCD, jump to the tutorial 1st part).
Anyway, With your code above U can't achieve your task. U don't have any async block which run at the end of the requests.
Edit:
Use AFNetworking:
U must remove your for loop first, and then do like this:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
[manager POST:#"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { // HERE u can do your second request which uses the first response
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters_new = <USE_YOUR_DATA_FROM_responseObject>;
[manager POST:#"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { // HERE u can do your third request which uses the first and second response
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
A simple way to do this is with recursion. Create a method that sends the url connection, and, once the connection is complete, calls itself to send it again.
Here's the key to the solution: make a method that can be called recursively, which sends requests and collects results. By calling itself recursively in the completion block, this method sees to it that each request starts after the previous one finishes...
// note - edited per the comments to get a new NSURLRequest each time
- (void)makeRequests:(NSInteger)count
results:(NSMutableArray *)results
completion:(void (^)(NSError *))completion {
// complete recursion
if (count == 0) return completion(nil);
NSURLRequest *request = [self nextRequest];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!error) {
[results addObject:data];
[self makeRequests:count-1 results:results completion:completion];
} else {
completion(error);
}
}];
}
To call it, allocate an array that will carry the results...
- (void)makeManyRequests {
NSMutableArray *resultsArray = [NSMutableArray array];
[self makeRequests:10 results:resultsArray completion:^(NSError *error) {
NSLog(#"done. results are %#", resultsArray);
}];
}
EDIT - Its unclear in the OP how this request changes each time, but it sounds like you have that figured out. This is just your originally posted code in its own method. Its a good idea to factor this out so your code can be clear on how it forms a different JSON payload each time...
- (NSURLRequest *)nextRequest {
id finalJSON = // your app supplies...
// somehow, this changes each time nextRequest is called
NSString *APIKEY = // your app supplies
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:finalJSON options:NSJSONWritingPrettyPrinted error:&error];
if (!jsonData) {
NSLog(#"Error creating JSON object: %#", [error localizedDescription]);
}
// your request creation code, copied from the OP
NSString *url = [NSString stringWithFormat:#"abc.com/folders"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"application/json;charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:APIKEY forHTTPHeaderField:#"X_API_KEY"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
return request;
}
I am finding for the way to run 2 services in a method one after another to post images one by one . after the 1st service i need to get response then i need pass that response to 2nd service.
The code i've used to post run a single service to post single image is
NSString *url=[NSString stringWithFormat:#"http://37.187.152.236/UserImage.svc/InsertObjectImage?%#",requestString];
NSLog(#"url1%#",url);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage1, 0.2f);
[request addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
some similar questions may be there in stackoverflow but my need is completely different.
Flow of method must be like this
*Run 1st url --> generate response ({userid:"20",message:"success"} ) --> run 2nd url *
help me, thanks in advance for everyone.
you can call the second method with respect to the response of first method
-(void)webservicecall {
WebApiController *obj=[[WebApiController alloc]init];
NSMutableDictionary *imageparameter = [NSMutableDictionary dictionary];
NSData *imagedata = UIImagePNGRepresentation(self.productImageView.image);
[imageparameter setValue:imagedata forKey:#"image"];
[obj callAPIWithImage:#"upload.php" WithImageParameter:imageparameter WithoutImageParameter:nil SuccessCallback:#selector(upload_response:Response:) andDelegate:self];
}
Response From Web Service:
-(void)upload_response:(NSString *)apiAlias Response:(NSData *)response {
NSMutableDictionary *jsonDictionary=[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil];
NSString *responseMsg=[[NSString alloc] initWithString:[jsonDictionary objectForKey:#"message"]];
if ([responseCode isEqualToString:#"success"]) {
[self CallToSecondWebService];
}
}
Second WebService:
-(void)CallToSecondWebService
{
}
http://codewithchris.com/tutorial-how-to-use-ios-nsurlconnection-by-example/
NSURLConnection synchronous request on https
how to send Asynchronous URL Request?
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/NSURLConnection_Class/Reference/Reference.html
You can read from all of these as per your choice..
Maybe this will help you.
-(void)getData:(NSString *)userid
{
/*--- Your Current code here ---*/
/*--- this is synchronous request you can use asynchronous as well ---*/
NSURLResponse *response = nil;
NSData *dataResponse = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
/*--- Save your response if you want ---*/
id Obj = [NSJSONSerialization JSONObjectWithData:dataResponse options:NSJSONReadingMutableLeaves error:nil];
if ([Obj isKindOfClass:[NSArray class]])
{
/*--- here you get response ---*/
/*--- I've created sample method that you can pass userid in same method ---*/
/*--- Call same method or create new method and do same thing ---*/
[self getData:[[Obj objectAtIndex:0] valueForKey:#"userid"]];
}
}
I would strongly discourage you in using sync connections, they block the thread until they have finished and if this thread is the main thread, they will block the user interactions. Also you will not have control on the chunk sent or auth challenges.
In your case most probably the best is to use a network manger such as AFNetworking 2 and creating different network operations, after that you can add dependencies between them (thus chaining them if you like).
The other way is dispatch_group. You can add the operations (or sessions) to a group and wait until they end.
[UPDATE]
In AFnetworking 2.0
NSDictionary * parameter = #{ParameterImage : mainImage ? #"1" : #"0",};
NSError * __autoreleasing * constructingError = nil;
AFHTTPRequestOperation * op1 = [self POST:ApiImageUploadURL parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:imagePath] name: ParameterImageData error:constructingError];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError * error = nil;
id objects = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];
DLog(#"Response %#", objects);
NSString * imageID = [objects[#"id"] stringValue];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DLog(#"Error%#", error);
}];
// create operation op2
[op2 addDependecy:op1];
I'm impementing an application in iOS7, it's kind of a social network app with posts with images and a backend that saves all of the data sent form the client. The iOS client is sending the information of the post via json and after the info is sent, it starts to send the image via multipart form using AFNetworking.
I need to be notified when the image is sent, so that I can refresh the main view of the app with the new posts, including the recently posted by the client. In the practice if I request the backend for the last posts and the multipart hasn't finished, the sending of the image gets interruped and fails to send the image.
The backend is develop in WCF and is a RESTful JSON web service.
Here is the method that sends the post to the backend:
+(void)addPostToServerAddtext:(NSString *)text addimage:(UIImage *)image addbeach:(NSString *)beach location:(NSString*)location;
{
NSLog(#"entro a addPost");
NSString *urlBackend = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"URLBackend"];
NSData* dataImage = UIImageJPEGRepresentation(image, 1.0);
NSString* ImageName = [NSString stringWithFormat:#"%#_%#.jpg",idUser ,dateToServer];
NSString *jsonRequest = [NSString stringWithFormat:#"{\"Date\":\"%#\"...."];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#newPost",urlBackend]];
NSMutableURLRequest *request = [ [NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
if (image != nil) {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:[NSString stringWithFormat:#"%#FileUpload",urlBackend]
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:dataImage name:#"image" fileName:ImageName mimeType:#"image/jpg" ];
}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
}
A couple of thoughts:
You say:
The iOS client is sending the information of the post via json and after the info is sent, it starts to send the image via multipart form using AFNetworking.
Technically, you're not waiting for the information to be sent, but you're doing these concurrently. Do you want these to be concurrent? Or sequential? Or why not just a single request that posts the information as well as the image?
I'd suggest using AFNetworking for both requests. You've got a powerful framework for managing network requests, and it feels awkward to see hairy NSURLConnection code in there.
If you keep the NSURLConnection code in there, note that you do not want to start a NSURLConnection, unless you used initWithRequest:delegate:startImmediately: with NO for that last parameter. You're effectively starting it twice, which can cause problems. I'd suggest removing the start call.
Setting all of that aside, what you want to do is to add a completion block parameter to your method, e.g., something like:
+ (void)addPostToServerAddtext:(NSString *)text addimage:(UIImage *)image addbeach:(NSString *)beach location:(NSString*)location completion:(void (^)(id responseObject, NSError *error))completion
{
// ...
if (image != nil) {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:[NSString stringWithFormat:#"%#FileUpload",urlBackend] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:dataImage name:#"image" fileName:ImageName mimeType:#"image/jpg" ];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (completion) completion(responseObject, nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (completion) completion(nil, error);
}];
}
}
You'd then invoke that like so:
[Persistence addPostToServerAddtext:text addimage:image addbeach:nil location:annotation completion:^(id responseObject, NSError *error) {
if (error) {
// handle error
return
}
// otherwise use the responseObject
}];
Now, I don't know what parameters you want to return in your completion block (I'm assuming you wanted to return what the AFHTTPRequestOperationManager did), but just change the parameters for that completion block as suits your needs.
Unrelated to your original question, but I notice that you're building jsonRequest like so:
NSString *jsonRequest = [NSString stringWithFormat:#"{\"Date\":\"%#\"...."];
That's a little risky if any of those fields include user supplied information (e.g. what if the user used double quotes in the information provided). I'd suggest you build a dictionary, and then build the jsonRequest from that. It will be more robust. Thus:
NSDictionary *dictionary = #{#"Date" : date,
#"Message" : message};
NSError *error = nil;
NSData *request = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
if (error)
NSLog(#"%s: dataWithJSONObject error: %#", __FUNCTION__, error);
Or, if you use AFNetworking, I believe it will do this JSON conversion of your dictionary for you. But, bottom line, be very wary about creating JSON strings yourself, at least if the request might include any user supplied information.