Google Toolbox For Mac : testing [NSURLConnection sendSynchronousRequest:...] - iphone

I'm wondering how to test a synchronous request to assert the behavior of an API client depending on the server response.
As it's a good practice to be independent of the server (so the test run fast and don't rely on the internet connection), I'd like to return my own response. I don't know how to do this, since the request is synchronous :
NSURL *url = [self URL];
NSData *postData = [self postData];
NSMutableURLRequest *downloadRequest = [NSMutableURLRequest requestWithURL:url];
[downloadRequest setHTTPMethod:#"POST"];
[downloadRequest setHTTPBody:postData];
[downloadRequest setTimeoutInterval:10.0];
return downloadRequest;
NSURLResponse *response;
NSError *error = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:downloadRequest
returningResponse:&response
error:&error];
Do you have any suggestion on how to do this ?
I don't know if it's possible to override NSURLConnection for example, or if I should change my code, just for testing purposes.

I don't completely understand the first sentence of the question. I can say that you almost certainly want to make it asynchronous. A synchronous request will block the UI and if it takes too long iOS will force-quit your app. Your asynchronous request callbacks can then review the success/failure and then either call a delegate with the same response or a modified one, or post a notification that you've previously installed handlers for, again swapping the response or not as you wish.

Related

save sign up view controller text values on the server through php web service call using post method in iOS

i have sign up form in which i have the fields like first name,last name,gender,email,password,user image,age. i want to make save this user information on the server through php webservice call.how can i pass these parameters to service url? will i use the http request using post method to save the user info to server and when that user wants to log in iOS app , i may match the credencial for that user. in shore, i need a log in and sign up screen for my iOS app, please suggest me any tutorial
Thanks in advance to all of you
First you need nto create php script and then transfer data through NSURL.
NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.0.6/savedevicedata.php?Udid=%#&Flag=%d&DateTime=%#",uniqueIdentifier,Flag,FinalDate]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"%#",request);
[request setHTTPMethod:#"POST"];
//[request setHTTPBody:[NSString stringWithFormat:#"%#",rawStr]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
Try this Code just replaces the your field.

How to manage scheduled maintenance in iOS Application?

I am looking for a way to be able to handle scheduled maintenance in iPhone app. We are using web services(.Net/C#) in our application and recently we have increased number of servers to maintain trafic on website. So whenever web team uploading website, they are displaying website is on scheduled maintenance. for iPhone, i have written below code to handle timeout at the same time.
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
it will notify to user after 60.0 Sec. so users are complaining about Freezes iPhone application. Is there any other way to handle this? or Is there any other way to open any particular screen at the time of scheduled maintenance?
Any help would be greatly appreciated! Thanks.
iOS 7 silent background notifications might work for you in this case.
You need to execute this code on a separate thread. The easiest way to do this is using Grand Central Dispatch, like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSURLResponse *response = nil;
NSError *error = nil;
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
NSData *resultData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
// Add code to handle returningResponse.
// Error handling
if (error != nil) {
NSLog(#"An error occured! %#", error);
}
});

How to store the values in web server from i phone application

I am developing view based application.In my view i have register page in that page i have
some fields like Firstname, lastname,e mail ID. When we click save button after entering the values these all field should be store in in webserver.In webserver i have application that application was developed using .net MVC Architecture and database is MYSQL .How i can store these values in webserver.
thanks for your response i have written this code is it right way to store values in webserver
-(IBAction)buttonClick:(id)sender
{
NSString* firstname = nameInput.text;
NSString* lastname = passInput.text;
NSString* bname = lastInput.text;
NSString *post =
[[NSString alloc] initWithFormat:#"fname=%#&lname=%#&email=%#",firstname,lastname,bname];
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest * request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.yoursite.com/file.php?%#",post]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) NSLog(#"Connection Successful");
}
#end
You have two options:
1) Develop a proper API that your iOS app can call using libraries like ASIHTTPRequest or AFNetworking
2) Have a .NET form processor in place, just like you would to process an HTML form, and then use ASIHTTPRequest, AFNetworking, or something similar to submit the request to this processor using the POST method and with the parameters you would like to store added to the request. This simulates an HTML form that has been filled and submitted, and then you can do whatever you wish with the data .NET receives. Both ASI and AFNetworking have pretty extensive documentation on how these types of requests are implemented on iOS with their respective libraries. Unfortunately, ASI is no longer being maintained, so I would recommend going with AFNetworking if possible.
RESPONSE TO UPDATE:
I only gave it a quick look over, but everything looks good to me. The only thing I would change is this:
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.yoursite.com/file.php?%#",post]]];
to this:
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.yoursite.com/file.php"]]];
What you will need now is code on the web side in that file.php that can process the request. It would use the typical $_POST['var_name_here'] to grab the data that is passed to it.
You have to implement a webapplication in your preferred language and deploy it to some webserver or hosting service. To get started, you should choose a language PHP, Java, Python, C# or whatever and google how you could implement a webservice within that language.
I would do this in Java and implement a RESTful wbeservice that sends and receives JSON or XML.

when is a response code received during a request for an image using ASIHTTPRequest?

When do I actually get my response code 200 for a valid request for an image? Is it after all of the data has been downloaded to my browser or which ever device is requesting the image?
I am using the library http://allseeing-i.com/ASIHTTPRequest/ to download images in my iPad app and using the download directly to a file option and then deleting the file if it was a 404 error or any other status code than 200.
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:#"/Users/ben/Desktop/my_file.jpg"];
Problem is partial responses seem to be getting saved during slow connections so I end up with blank or corrupt images.
I decided instead to save the data stream to disk only after I received a status code of 200:
NSURL *url = [NSURL URLWithString: [[NSString stringWithFormat:kProductImagesURL, fileName] stringByAppendingString:tStamp]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setTimeOutSeconds:10];
[request startSynchronous];
int statusCode = [request responseStatusCode];
if (statusCode==200) {
NSData *responseData = [request responseData];
[responseData writeToFile:[savePath stringByReplacingOccurrencesOfString:#"%20" withString:#" "] atomically:YES];
}
I just want to make sure that the response code only comes back after the request has been completed and all of the data has been downloaded. I am 99% sure that is the case but can't afford another app release with an image bug like this in it.
There are two reasons you should probably consider switching to an asynchronous request. The first is, it frees up your main thread to interact with the user (even a modal spinner would be nice--otherwise it looks like your app has frozen).
Second, it gives you callbacks that only happen once the whole request is finished. I can't really explain only having gotten partial data with the code you showed, but I've never once had that problem using ASI's asynchronous methods.

iPhone: Post data to php page

Despite looking at similar posts on this site and google, I just can't wrap my head around how to post to a php page from the iPhone. Here is what I want to do:
I have a php script, say at www.mypage.com/myscript.php that I could post to normally by doing www.mypage.com/myscript.php?mynumber=99&myname=codezy
This in turn will add a log message in database for example. I do not want any data back, it is essentially a one way transaction. NSMutableURLRequest seems to be what I am looking for but I just cant get a handle on how to make this work with a couple parameters.
If you're sending a single URL request without needing to send multiple variations, NSURLRequest will do. Even though you are using multiple parameters, they are all part of the same URL, so you just treat them that way. Build the URL as a string first and then use the string to initialize a NSURL object.
You are prompting a log message on the server, but you will want to have response data in case something goes wrong. You can just ignore the response data unless there's an error. The request is sent using a NSURLConnection object.
NSURL *urlToSend = [[NSURL alloc] initWithString: #"www.mypage.com/myscript.php?mynumber=99&myname=codezy"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:urlToSend
cachePolicy:NSURLRequestReturnCacheDataElseLoad
cachetimeoutInterval:30];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];