Present HUD before posting values to server - ios

Hi I'm using this code to send post values to a server but I want the HUD to appear during the time the request is being done, because it appears only when it ends the request.
-(IBAction)sendk:(id)sender {
/*HUD*/
SLHUD *hudView = [SLHUD Mostrar:self.view]; // Creates a Hud object.
hudView.text = #"Please Wait"; // Sets the text of the Hud.
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityIndicator.alpha = 1.0;
activityIndicator.center = CGPointMake(160, 280);
activityIndicator.hidesWhenStopped = NO;
[activityIndicator setTag:899];
[self.view addSubview:activityIndicator];
[activityIndicator startAnimating];
/*FIN HUD*/
NSString *post =[[NSString alloc] initWithFormat:#"user=%#&pass=%#",[username text],[password text]];
NSLog(#"%#",post);
NSURL *url=[NSURL URLWithString:#"URL TO SERVER"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"%ld",(long)[response statusCode]);
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseData);

The problem is that the code is blocking the main thread until the network request finishes. The screen will only update after the sendk method returns, but the method won't return until the sendSynchronousRequest method is finished. The solution is to dispatch the networking code (everything after /*FIN HUD*/) onto a background thread, or use sendAsynchronousRequest, and use the completion block to notify the main thread when the response arrives.
The code framework for using a background thread looks like this
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
// do networking stuff here
dispatch_async( dispatch_get_main_queue(), ^{
// turn off the HUD and remove the spinner here
// also do something with the network response here
});
});

Related

POST method receive duplicated in server

I'm sending a POST request to server but they receive it duplicated with the same date and even time. this is my code :
-(void) getTerms{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
User *mUser = [[User alloc]init];
NSString *appFile1 = [self getUserFile];
mUser = [NSKeyedUnarchiver unarchiveObjectWithFile:appFile1];
NSString *post = [NSString stringWithFormat:#"Method=GetFAQ&CustomerID=%#",mUser.customerID];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[ServerName serverName]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
if( theConnection ){
// other codes
}
});
});
}
I just wonder what is wrong with my code ? thanks in advance
this is how i solved the problem :
-(void) getCredit{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *post = [NSString stringWithFormat:#"Method=%#",mMethod];
NSMutableURLRequest *request = [ServerName postToServer:post];
dispatch_async(dispatch_get_main_queue(), ^{
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSString *jsonString = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSUTF8StringEncoding];
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSDictionary *res1 = [res objectForKey:#"ServerResponse"];
});
});
}

Synchronous NSURLConnection https post request with JSON

I need to make a HTTPS post request to a server using a synchronous connection. I've made plenty of http connections but for some reason the code doesn't work with https and I'm sure the website address is right.
Some of my code:
Note that dparam is a dictionary object.
NSError *err;
NSData *parameterJSONData = [NSJSONSerialization dataWithJSONObject:dparam options:
NSJSONWritingPrettyPrinted error:&err];
NSString *param = [[NSString alloc] initWithData:parameterJSONData encoding:NSUTF8StringEncoding];
NSString *post =[[NSString alloc] initWithFormat:#"varnameOne=%#&varnameTwo=%#&param=%#",vone,vtwo,param];
//my_url is a string defined elsewhere
NSURL *url=[NSURL URLWithString:my_url];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
I need to do this synchronously as I don't really have the time to change all my database calls to asynchronous and the calls need to either complete or fail before the program continues so it'd have to be made effectively synchronous anyway.
That said I did try a synchronous route but it didn't work with https only http.

NSOperationQueue run same task again on response iOS

In my project I need to send data to server, for that I've used the following code to achieve the task:
- (void)sendJSONToServer:(NSString *) jsonString
{
// Create a new NSOperationQueue instance.
operationQueue = [NSOperationQueue new];
//
// Create a new NSOperation object using the NSInvocationOperation subclass to run the operationQueueTask method
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:#selector(operationQueueTask:)
object:jsonString];
// Add the operation to the queue and let it to be executed.
[operationQueue addOperation:operation];
}//End of sendJSONToServer method
-(void) operationQueueTask:(NSString *) jsonString
{
//NSOperationQueue *remoteResultQueue = [[NSOperationQueue alloc] init];
dispatch_queue_t myQueue = dispatch_queue_create("SERVER_QUEUE",NULL);
dispatch_async(myQueue, ^{
// Performing long running process
// Sending json data to server asynchronously
NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[jsonString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MY_URL_eg_http://www.example.com"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"Response is:%#",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}];
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
NSLog(#"Thread Process Finished");
});
});
}//End of operationQueueTask method
By the above code I'm able to send data and get response.
But when there is no internet the data will not be sent to server. How to handle this situation based on the response we get.
Let's say we get response success on fair condition ans false on worst condition.
UPDATED CODE FOR RETRIES
-(id)init
{
self = [super init];
if (self != nil)
{
//initialize stuffs here
pendingOperationQueue = [[NSMutableArray alloc] init];
operationQueue = [NSOperationQueue new];
}
return self;
}//End of init method
- (void)sendJSONToServer:(NSString *) jsonString
{
NSOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(operationQueueTask:) object:[NSString stringWithString:[pendingOperationQueue objectAtIndex:0]]];
[operation start];
}//End of sendJSONToServer method
-(void) operationQueueTask:(NSString *) jsonString
{
//NSOperationQueue *remoteResultQueue = [[NSOperationQueue alloc] init];
dispatch_queue_t myQueue = dispatch_queue_create("SERVER_QUEUE",NULL);
dispatch_async(myQueue, ^{
// Performing long running process
// Sending json data to server asynchronously
NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[jsonString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MY_URL_http://www/example.com"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"Response is:%#",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
if([[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] rangeOfString:#"true"].location == NSNotFound)
{
// Add the operation to the queue and let it to be executed.
NSLog(#"Failed To Add To Server, Rerunning the task");
}
else
{
NSLog(#"Successfully Added To Server");
NSLog(#"ADDED_DATA_TO_SERVER: %#", jsonString);
if([pendingOperationQueue count] > 0)
{
[pendingOperationQueue removeObjectAtIndex:0];
if([pendingOperationQueue count] > 0)
{
NSOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(operationQueueTask:) object:[NSString stringWithString:[pendingOperationQueue objectAtIndex:0]]];
[operation start];
}
}
}
}];
});
}//End of operationQueueTask method
Heads up! This is a long answer. TL;DR: You can't re-run an NSOperation, but you can design your classes and methods to make it easy to retry requests.
First a quick answer to your title question: you can't re-run an NSOperation, they're not designed to do that. From the docs:
An operation object is a single-shot object — that is, it executes its
task once and cannot be used to execute it again.
With that out of the way, lets take a look at what you're currently doing and clean it up a bit so that re-using it is easier. There's a ton of async stuff going on in there that you don't need; I'll go through it piece by piece.
Let's start with your operationQueueTask: method. The first thing you do in the method is:
dispatch_queue_t myQueue = dispatch_queue_create("SERVER_QUEUE",NULL);
That means that every time that method is called, you're creating a new dispatch queue. While you can do that if you really want to, that's not what dispatch queues are really designed for. A better idea would be to use one of the background queues that are already available:
dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
Next you are dispatching a block asynchronously to that queue. That block:
Sets up your NSMutableURLRequest.
Calls [NSURLConnection sendAsynchronousRequest:...].
Dispatches another block (which has a comment in it about updating the UI) to the main queue.
1 and 2 are fine, I don't see anything you need to change there. 3, however, is problematic because of where that dispatch is being called. The way you have it setup now, NSURLConnection will fire off its asynchronous request and then, before that even has a chance to run, you fire off the block to the main queue to update the UI. What you need to do instead is fire off that block in the completion handler passed to [NSURLConnection sendAsynchronousRequest:...]. Like so:
[NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"Response is:%#",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
NSLog(#"Thread Process Finished");
});
}];
Now, notice the name of the method you're calling on NSURLConnection? sendAsynchronousRequest:. It actually handles queuing the request on a background queue for you. Which mean, you don't actually need (or want) all the dispatch_* stuff at the beginning of this method. With that in mind, we can reduce it down to:
-(void) operationQueueTask:(NSString *) jsonString
{
NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[jsonString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MY_URL_eg_http://www.example.com"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"Response is:%#",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
NSLog(#"Thread Process Finished");
});
}];
} //End of operationQueueTask method
Now, on to your sendJSONToServer: method. You're doing a similar thing here that you did at the start of operationQueueTask:: you're creating a new NSOperationQueue each time it runs; that's also not needed (nor typically wanted). What you should probably be doing is creating that operationQueue when your class is initialized (it looks like it's already an instance variable on your class, so you're good there):
// NOTE: I'm just using a default initializer here; if you already have an initializer, use that instead
- (instancetype)init {
if (self = [super init]) {
operationQueue = [NSOperationQueue new];
}
return self;
}
That gets rid of your first line. Next, you're creating an NSInvocationOperation which calls operationQueueTask: and then adding it to your operationQueue. Since you've been re-creating your operationQueue every time, I'm going to assume that it isn't used for anything other than these server requests. In that case, you actually don't need to do this on your operationQueue at all because, as we discovered in the previous method, NSURLConnection is already handling all the background threading for you. In that case, we can actually just copy the code from operationQueueTask: to sendJSONToServer: and get rid of operationQueueTask: altogether. That makes it look like:
- (void)sendJSONToServer:(NSString*)jsonString {
NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[jsonString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MY_URL_eg_http://www.example.com"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"Response is:%#",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
NSLog(#"Thread Process Finished");
});
}];
}
Note: We still need to keep operationQueue around since we pass it to [NSURLConnection sendAsynchronousRequest:... as the queue that it should run on.
So, how do we go about retrying the request when it fails? The simplest method is to add a recursive function that calls itself when the request fails. You'll pass this method the jsonString you want to send and the maximum number of times it should try to send it before it gives up for good.
To facilitate that, lets make one more change to you existing function: instead of handling the completion block inside the function, lets make the completion block a parameter you pass to the function so that it can be processed elsewhere.
- (void)sendJSONToServer:(NSString*)jsonString withCompletionHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError))completionHandler {
NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[jsonString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MY_URL_eg_http://www.example.com"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:completionHandler];
}
Now, lets build that recursive function. I'll call it:
- (void)sendJSONToServer:(NSString*)jsonString withRetryAttempts:(NSUInteger)retryTimes;
The basic flow will be:
Check if retryTimes is greater than 0
If it is, attempt to send the request to the server
When the request finishes, check the response for success
If successful, update the UI on the main queue
If not successful, subtract one from retryTimes and call this function again
That looks something like:
- (void)sendJSONToServer:(NSString*)jsonString withRetryAttempts:(NSUInteger)retryTimes {
if (retryTimes > 0) {
[self sendJSONToServer:jsonString withCompletionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"Response is:%#",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
if (/* check response to make sure it succeeded */) {
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
NSLog(#"Thread Process Finished");
});
} else {
// Note: you can add a dispatch_after here (or something similar) to wait before the next attempt
// You could also add exponential backoff here, which is usually good when retrying network stuff
[self sendJSONToServer:jsonString withRetryAttempts:(retryTimes - 1)];
}
}];
} else {
// We're out of retries; handle appropriately
}
}
Note: There are some bits in there that are just comments because they are application specific; they'll need to be implemented before that code will compile/run.
Now, instead of calling [yourClass sendJSONToServer:jsonString], call: [yourClass sendJSONToServer:jsonString withRetryTimes:maxRetries] and, if the request fails, it should retry up to maxRetries times.
One last note: As #Deftsoft mentioned, Apple's Reachability classes are a nice way to know if you have an active connection to the network or not. It's a good idea to check that first before trying to call sendJSONToServer:withRetryTimes:. That way you're not trying to make requests when it's not possible to even connect in the first place.
You can Apple reachability classes below is the reference code which will provide you the better idea.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(networkChanged:) name:kReachabilityChangedNotification object:nil];
reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
- (void)networkChanged:(NSNotification *)notification
{
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == NotReachable) { NSLog(#"not reachable");}
else if (remoteHostStatus == ReachableViaWiFiNetwork) { NSLog(#"wifi"); }
else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { NSLog(#"carrier"); }
}

UILabel value changes after a long time

I have a UIView and in it I have a UILabel , when i press a button i receive data from server and I want to change the text in the label according to the new data, i have managed to do that but it takes a long time (about a minute) to change the text.
does anybody have an idea why? because I use NSLog to show lbl.text after changing and it show the new data but on screen it take time to change..
NSLog(#"Sending Data to Server");
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSLog(#"post: %#",post);
NSString *postLength = [NSString stringWithFormat:#"%ld", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *urlstring = [NSString stringWithFormat:JSON_URL];
[request setURL:[NSURL URLWithString:urlstring]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
dispatch_async(dispatch_get_main_queue()
NSError *error;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (!error) {
_jsonResults = [NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error];
Label.text = [NSString stringWithFormat:#"you have: %#",[_jsonResults objectForKey:#"num"]];
I Have edit my answer , now it work fine, i updated my label on a background thread only, so i added
dispatch_async(dispatch_get_main_queue()
and now it works great!
i was doing it in the back end an thats why it took so much time to change,
i add this
dispatch_async(dispatch_get_main_queue()
and now it works fine!

Application UI hangs due to networking , iOS

I am developing an iOS application where i am implementing push notifications.
In the AppDelegate and more specifically in the didRegisterForRemoteNotificationsWithDeviceToken function , after i register for push notifications , i make an http post request to send to my server the users credentials (cfuuid , os , etc..) and the push token.
When the server is app everything goes smoothly. However , if for any reason the server is unreachable the UI of the application hangs for around 30 seconds (till the connection timeOut) and the only thing i see is a white screen.
How could i separate the "networking" from the UI ? I guess the answer is by using another thread.
How exactly could i do that ? The only thing i am doing inside the didRegisterForRemoteNotificationsWithDeviceToken is use ASIHTTPRequest library to send the credentials to the server.
The code that needs to be executed in the different thread looks like this :
NSString *jsonString;
//jsonString = [[NSString alloc] initWithFormat:#"{\"deviceUUID\":\"%#\",\"os\":\"ios\", \"active\":\"%d\", \"pushToken\":\"%#\"}",deviceUUID,active,token];
jsonString = [[NSString alloc] initWithFormat:#"{\"deviceUUID\":\"%#\",\"os\":\"ios\", \"pushToken\":\"%#\"}",deviceUUID,token];
NSLog(#"%#",jsonString);
//NSString *urlStr= [[NSString alloc] initWithFormat:CITYINFO_SERVER_URL,#"push_notifications/register"];
NSString *urlStr= [[NSString alloc] initWithFormat:CITYINFO_SERVER_URL,#"register.php"];
//send json file , using ASIHttpClass
NSURL *url = [NSURL URLWithString:urlStr];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
request.timeOutSeconds = TIME_OUT_SECONDS;
[request setRequestMethod:#"PUT"];
//NSString *credentials= [self encodeCredentials];
//[request addRequestHeader:#"Authorization" value:[[NSString alloc] initWithFormat:#"Basic %#",credentials]];
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
[request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
if([request responseStatusCode]==200){
NSLog(#"Server reached. Response Status : 200");
return true;
} else {
NSLog(#"Server could not be reached");
return false;
[request startSynchronous];
Never. Do. Synchronous. Networking. On the main thread.
Move it to another thread, or even better, make the request async.
Instead of sending a synchronous request just send Asynchronous request
[request startAsynchronous];
And call the method which is hitting service after some time interval from delegate method.
use [request startAsynchronous];
instead of [request startSynchronous];
I think , you are use main thread for send device token to server,please use the secondary thread for this functionality
try this code :-
[self performSelectorInBackground:#selector(pushNotifictionJson) withObject:nil];
-(void) pushNotifictionJson
{
NSString *jsonString;
//jsonString = [[NSString alloc] initWithFormat:#"{\"deviceUUID\":\"%#\",\"os\":\"ios\", \"active\":\"%d\", \"pushToken\":\"%#\"}",deviceUUID,active,token];
jsonString = [[NSString alloc] initWithFormat:#"{\"deviceUUID\":\"%#\",\"os\":\"ios\", \"pushToken\":\"%#\"}",deviceUUID,token];
NSLog(#"%#",jsonString);
//NSString *urlStr= [[NSString alloc] initWithFormat:CITYINFO_SERVER_URL,#"push_notifications/register"];
NSString *urlStr= [[NSString alloc] initWithFormat:CITYINFO_SERVER_URL,#"register.php"];
//send json file , using ASIHttpClass
NSURL *url = [NSURL URLWithString:urlStr];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
request.timeOutSeconds = TIME_OUT_SECONDS;
[request setRequestMethod:#"PUT"];
//NSString *credentials= [self encodeCredentials];
//[request addRequestHeader:#"Authorization" value:[[NSString alloc] initWithFormat:#"Basic %#",credentials]];
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
[request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
if([request responseStatusCode]==200){
NSLog(#"Server reached. Response Status : 200");
return true;
} else {
NSLog(#"Server could not be reached");
return false;
}
}
and second method
use [request startAsynchronous];
instead of [request startSynchronous];

Resources