I was recently looking at an example from apple about NSURLConnection and I tried implementing it into my code but I am not sure if am I doing it right.
Basically I want the connection to go to my website where I have it connected to a php script that runs the search within my database and then echo’s it to the browser. I want the iphone to take the line that is echoed and hold it into a string variable. This is my code.
Is this correctly done?
Thank you in advance
NSString *stringToBeSent= [[NSString alloc] initWithFormat:
@"http:/xxxxx/siteSql.php? data=%@",theData];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:
[NSURL URLWithString:stringToBeSent]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere... in my .h file
// NSMutableData *receivedData;
receivedData = [[NSMutableData data] retain];
//convert NSMutableData to a string
NSString *stringData= [[NSString alloc]
initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog (@"result%@", receivedData);
} else {
// Inform the user that the connection failed.
NSLog(@"failed");
}
I think you might be missing a couple things:
In the method that you use to trigger retrieving the data make sure you release the old data before initializing:
I assume that space is a typo or something for the URL?
You don’t need to call
requestWithURL:cachePolicy:timeoutInterval:requestWithURL:uses the same defaults as you chose.The data will come in blocks. You’ve got to handle that over time, outside this method, using the delegate method
connection:didReceiveData:, like so:Similarly, if you want something done with the data once it’s all received, you do it in
connectionDidFinishLoading:NOTE THAT THE CONNECTION IS RELEASED so it has to be defined in your header as an instance variable (eg.NSURLConnection *connection;Also look into the other delegate methods like
connection:didFailWithError:You probably want to release the connection and stringData there as well, in case of an error.I hope that’s of some help! Enjoy!