Slow Multiple URL retreival in iOS code - objective-c

I want to access a URL and retrieve data from this URL, based on the data retrieved I want to retrieve data from another URL
I tried accessing multiple URL in the following way:
- (void) showClassRoom:(NSString *)theMessage{
NSString *queryURL =[NSString stringWithFormat:#"http://nobert.cloudfoundry.com/CalOfEvents/tos"];
NSURL *url = [NSURL URLWithString: queryURL];
NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSError *error;
NSURLResponse *response;
NSData *returnData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
if(returnData){
NSString *strResult = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
NSDictionary *result = [strResult JSONValue];
for(id theKey in result){
for(id hello in theKey){
NSLog(#"The key:%#, The value:%#",hello,[theKey objectForKey:hello]);
}
}
if(TRUE){//based on some condition secondShowClassRoom is called
[self secondShowClassRoom];
}
}
}
- (void) secondShowClassRoom{
NSString *queryURL =[NSString stringWithFormat:#"http://nobert.cloudfoundry.com/CalOfEvents/to"];
NSURL *url = [NSURL URLWithString: queryURL];
NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSError *error;
NSURLResponse *response;
NSData *returnData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
if(returnData){
NSString *strResult = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
NSDictionary *result = [strResult JSONValue];
for(id theKey in result){
for(id hello in theKey){
NSLog(#"The key:%#, The value:%#",hello,[theKey objectForKey:hello]);
}
}
}
}
This retrieves the data VERY SLOWLY and my app requires very fast access as I am developing an application on Augmented Reality
There is another method that is faster however I am not able to access multiple URLs:
- (void) showClassRoom:(NSString *)theMessage{
NSString *queryURL =[NSString stringWithFormat:#"http://nobert.cloudfoundry.com/CalOfEvents/to"];
NSURL *url = [NSURL URLWithString: queryURL];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn) {
webData = [[NSMutableData data] retain];
}
classRoomControl.hidden = NO;
labControl.hidden = YES;
placementControl.hidden = YES;
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *) response{
[webData setLength: 0]; }
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *) data {
[webData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *) error {
[conn release];
[webData release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
[conn release];
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *strResult = [[NSString alloc] initWithBytes:[webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSDictionary *result = [strResult JSONValue];
for(id theKey in result){
for(id hello in theKey){
NSLog(#"The key:%#, The value:%#",h,hello);
}
}
[strResult release];
[webData release];
}
Please Help me with this.Any help would be appreciated..

You are right on track preferring the asynchronous model for network communication (since synchronous communication will block your UI unless you handle it in a separate thread).
The correct way to chain multiple asynchronous network request is doing one request after another in the callbacks (i.e., in connectionDidFinishLoading; when one request is done, you send the next one).
One more suggestion is not using NSURlRequest/NSURLConnection for that, since they make thinks unnecessarily complex, and try with a framework like AFNetworking.

Related

JSON returning data but data parameter is nil

I'm messing with some API stuff and tried the following:
#define searchWebService #"https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=b667841296224aab0371a6f4a4546662&format=json&per_page=20&page=1"
// Construct url string for search
NSString *urlString = [NSString stringWithFormat:#"%#&text=%#&nojsoncallback=1", searchWebService, keyword];
//NSString *formattedURLString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// Create url via formatted string
NSURL *url = [NSURL URLWithString:urlString];
// Get all data from the return of the url
NSData *photoData = [NSData dataWithContentsOfURL:url];
// Place all data into a dictionary
NSDictionary *allData = [NSJSONSerialization JSONObjectWithData:photoData options:kNilOptions error:nil];
Here is the URL that is built:
https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=b667841296224aab0371a6f4a4546662&format=json&per_page=20&page=1&text=ball&nojsoncallback=1
When I plug this URL into a web browser I get formatted JSON but when I try to plug that into:NSData *photoData = [NSData dataWithContentsOfURL:url];
I get 'data parameter is nil'.
Any ideas what I'm doing wrong?
UPDATE:
I'm now using:
// Construct url string for search
NSString *urlString = [NSString stringWithFormat:#"%#&text=%#&nojsoncallback=1", searchWebService, keyword];
NSString *formattedURLString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:theRequest queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(#"BOOM %s %#", __func__, response);
if(!connectionError){
}
else{
NSLog(#"%s %#", __func__, connectionError.localizedDescription);
}
but neither of the logs ever show in the console.
UPDATE: TEST PROJECT
I've created a brand new project and put the following code in the viewDidLoad method:
NSString *urlString = [NSString stringWithFormat:#"%#", webServiceGetGlobalScores];
NSString *formattedURLString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:formattedURLString]];
NSLog(#"theRequest: %#", theRequest);
[NSURLConnection sendAsynchronousRequest:theRequest queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(#"BOOM %s %#", __func__, response);
if(!connectionError){
}
else{
NSLog(#"%s %#", __func__, connectionError.localizedDescription);
}
}];
And this is the defined #define webServiceGetGlobalScores #"http://www.appguys.biz/JSON/iTapperJSON.php?key=weBeTappin&method=getGlobalScores"
But still the sendAsynchronousRequest does not log anything.
UPDATE 3
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Construct url string for search
NSString *urlString = [NSString stringWithFormat:#"%#", webServiceGetGlobalScores];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSLog(#"urlRequest: %#", urlRequest);
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{NSLog(#"BOOM %s %#", __func__, response);
NSLog(#"ERROR: %#", error);
if ([data length] > 0 && error == nil){
NSLog(#"BOOM");
}
}];
}
Try using + dataWithContentsOfURL:options:error: instead, which gives you an NSError object. Plus, notice that that the docs say:
Do not use this synchronous method to request network-based URLs. For
network-based URLs, this method can block the current thread for tens
of seconds on a slow network, resulting in a poor user experience, and
in iOS, may cause your app to be terminated.
Instead, for non-file URLs, consider using the
dataTaskWithURL:completionHandler: method of the NSSession class. See
URL Loading System Programming Guide for details.
You can use this code for downloading data,
NSString *urlString = //your whatever URL
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:theRequest queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(#"%s %#", __func__, response);
if(!connectionError){
//Parse your JSON data
}
else{
NSLog(#"%s %#", __func__, connectionError.localizedDescription);
}
}];
Edited
Other way works!!! o_O see following
Now i surprised why following code working instead of above.
NSString *urlString = #"https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=b667841296224aab0371a6f4a4546662&format=json&per_page=20&page=1&text=ball&nojsoncallback=1";
NSString *formattedURLString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSError *theErr;
NSData *thd = [NSData dataWithContentsOfURL:[NSURL URLWithString:formattedURLString] options:0 error:&theErr];
if(theErr){
NSLog(#"%#", theErr.localizedDescription);
}
else{
NSLog(#"%#", [[NSString alloc] initWithData:thd encoding:NSUTF8StringEncoding]);
}
3rd Way,
Newer iOS simulator version > 6.x having some issue. Reset your simulator and check it out your code.
For reference go NSURLConnection GET request returns -1005, "the network connection was lost"

Objective-C how to convert nsdata from web service to nsarray

How do i convert id to an array?
I have an apple app that talks to a server.
Issue i have is the app returns the data in the form of id however i need to convert this to an array as the actual returned data looks like the following.
[["30","2",1],["15","67",1],["30","4",1]]
It is actually the output from a mysql server
The actual app code looks like the following
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"blah blah"]];
NSURL_Layer * connection = [[NSURL_Layer alloc]initWithRequest:request];
[connection setCompletitionBlock:^(id obj, NSError *err) {
if (!err) {
//Need to convert the id to nsarray here, dunno how
} else {
//There was an error
}
}];
[connection start];
The NSURL.h
-(id)initWithRequest:(NSURLRequest *)req;
#property (nonatomic,copy)NSURLConnection * internalConnection;
#property (nonatomic,copy)NSURLRequest *request;
#property (nonatomic,copy)void (^completitionBlock) (id obj, NSError * err);
-(void)start;
NSURL.m
-(id)initWithRequest:(NSURLRequest *)req {
self = [super init];
if (self) {
[self setRequest:req];
}
return self;
}
-(void)start {
container = [[NSMutableData alloc]init];
internalConnection = [[NSURLConnection alloc]initWithRequest:[self request] delegate:self startImmediately:YES];
if(!sharedConnectionList)
sharedConnectionList = [[NSMutableArray alloc] init];
[sharedConnectionList addObject:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[container appendData:data];
}
//If finish, return the data and the error nil
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
if([self completitionBlock])
[self completitionBlock](container,nil);
[sharedConnectionList removeObject:self];
}
//If fail, return nil and an error
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if([self completitionBlock])
[self completitionBlock](nil,error);
[sharedConnectionList removeObject:self];
}
Update:
i have added
NSURL_Layer * connection = [[NSURL_Layer alloc]initWithRequest:request];
[connection setCompletitionBlock:^(id obj, NSError *err) {
if (!err) {
NSError* error;
NSArray* array = [NSJSONSerialization JSONObjectWithData:obj options:NSJSONReadingAllowFragments error:&error];
} else {
//There was an error
}
}];
[connection start];
but returns error
error NSError * domain: #"NSCocoaErrorDomain" - code: 3840
_userInfo NSDictionary * 1 key/value pair
[0] (null) #"NSDebugDescription" : #"Invalid value around character 0."
Update: I put
NSLog(#"Data as string:%#", [[NSString alloc]initWithData:obj encoding:NSUTF8StringEncoding]);
which gave me a strange feedback. As a result i looked at my url request full code is below.
NSString *post = [NSString stringWithFormat:#"unique_id=%#&unique_password=%#",ServerUniqueID,ServerPassword];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"blah blah"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURL_Layer * connection = [[NSURL_Layer alloc]initWithRequest:request];
[connection setCompletitionBlock:^(id obj, NSError *err) {
if (!err)
{
NSError* error;
NSArray* array = [NSJSONSerialization JSONObjectWithData:[NSData dataWithData: obj] options:NSJSONReadingAllowFragments error:&error];
NSLog(#"Data as string:%#", [[NSString alloc]initWithData:obj encoding:NSUTF8StringEncoding]);
int temp = array.count;
}
else
{
//There was an error
}
}];
[connection start];
if i remove
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
it works
if its in it dosn't so i have a whole new issue to look into.
you save the bytes into a container variable, alas the id infact NSData
(note id is just a 'wildcard pointer' that means ANY objC object)
so your id is NSData and from what you show it seems to be 3 json arrays... but no real JSON... (["30","2",1]["15","67",1]["30","4",1] isn't anything)
EITHER make the server send you JSON and THAT you can parse into a dictionary/array using NSJSONSerialization
OR write a custom separator to convert the data

Objective C NSURLConnection dosen't get response data

I am creating this application, it communicates with a PHP script on my web-server.
Last night it was working perfectly. But today two of the connections does not get response.
I've tried the NSURL link in my browser, it works fine. Also one of the connections work, but as i said two connections does not work?
- (void) getVitsTitelByID:(int)id {
NSString *url = [NSString stringWithFormat:#"http://webserver.com /ivitserdk.php?function=gettitelbyid&id=%d", id];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1.0];
connectionTitelByID = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
connectionDidReciveData:
if(connection == connectionTitelByID){
responseTitel = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
connectionDidFinishLoading:
if(connection == connectionTitelByID){
titelLabel.text = responseTitel;
}
I've tried and debugging it.
responseTitel seems to be (null).
Help would be apriceated :)
didReceiveData may be called N (several) times. save the data to a mutably data buffer (queue it up) and in didFinish read it into a string
mock code:
- (void) getVitsTitelByID:(int)identifier {
NSString *url = [NSString stringWithFormat:#"http://webserver.com/ivitserdk.php?function=gettitelbyid&id=%d", identifier];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1.0];
connectionTitelByID = [[NSURLConnection alloc] initWithRequest:request delegate:self];
dataForConnectionTitelByID = [NSMutableData data];
[connectionTitelByID start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if(!data.length) return;
if(connection == connectionTitelByID)
[dataForConnectionTitelByID appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if(connection == connectionTitelByID) {
id str = [[NSString alloc] initWithData:dataForConnectionTitelByID encoding:NSUTF8StringEncoding];
NSLog(#"%#",str);
dataForConnectionTitelByID = nil;
connectionTitelByID = nil;
}
}

iOs receivedData from NSURLConnection is nil

I was wondering if anyone could point out why I'm not able to capture a web reply. My NSLog shows that my [NSMutableData receivedData] has a length of 0 the entire run of the connection. The script that I hit when I click my login button returns a string. My NSLog result is pasted below, and after that I've pasted both the .h and .m files that I have.
NSLog Result
2012-11-28 23:35:22.083 [12548:c07] Clicked on button_login
2012-11-28 23:35:22.090 [12548:c07] theConnection is succesful
2012-11-28 23:35:22.289 [12548:c07] didReceiveResponse
2012-11-28 23:35:22.290 [12548:c07] didReceiveData
2012-11-28 23:35:22.290 [12548:c07] 0
2012-11-28 23:35:22.290 [12548:c07] connectionDidFinishLoading
2012-11-28 23:35:22.290 [12548:c07] 0
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
// Create an Action for the button.
- (IBAction)button_login:(id)sender;
// Add property declaration.
#property (nonatomic,assign) NSMutableData *receivedData;
#end
ViewController.m
#import ViewController.h
#interface ViewController ()
#end
#implementation ViewController
#synthesize receivedData;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"didReceiveResponse");
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"didReceiveData");
[receivedData appendData:data];
NSLog(#"%d",[receivedData length]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"%d",[receivedData length]);
}
- (IBAction)button_login:(id)sender {
NSLog(#"Clicked on button_login");
NSString *loginScriptURL = [NSString stringWithFormat:#"http://www.website.com/app/scripts/login.php?"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:loginScriptURL]];
NSString *postString = [NSString stringWithFormat:#"&paramUsername=user&paramPassword=pass"];
NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:postData];
// Create the actual connection using the request.
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
// Capture the response
if (theConnection) {
NSLog(#"theConnection is succesful");
} else {
NSLog(#"theConnection failed");
}
}
#end
The issue is you are not initializing the receivedData instance. Just change your property like:
#property (nonatomic, retain) NSMutableData *receivedData;
And change the methods like:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"didReceiveResponse");
[self.receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"didReceiveData");
[self.receivedData appendData:data];
NSLog(#"%d",[receivedData length]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connectionDidFinishLoading");
NSLog(#"%d",[receivedData length]);
}
- (IBAction)button_login:(id)sender
{
NSLog(#"Clicked on button_login");
NSString *loginScriptURL = [NSString stringWithFormat:#"http://www.website.com/app/scripts/login.php?"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:loginScriptURL]];
NSString *postString = [NSString stringWithFormat:#"&paramUsername=user&paramPassword=pass"];
NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:postData];
// Create the actual connection using the request.
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
// Capture the response
if (theConnection)
{
NSLog(#"theConnection is succesful");
self.receivedData = [NSMutableData data];
} else
{
NSLog(#"theConnection failed");
}
}
Please try "%i" instead of %d in nslog
You can try the following code May be help you.
- (IBAction)button_login:(id)sender {
NSLog(#"Clicked on button_login");
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:#"user" forKey:#"Username"];
[dictionnary setObject:#"pass" forKey:#"Password"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = #"Sample URL";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
NSLog(#"%#", responseString);
}
if it is a GET Request then, can you try link : /login.php?username=admin&password=1212‌​3
- (IBAction)button_login:(id)sender {
NSLog(#"Clicked on button_login");
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"/login.php?username=adm‌​in&password=1212‌​3"]];
// Perform request and get JSON as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"response=%#",response );
}
and use this code.

iOS Get Connection

This is my first time on this site and I am very new to coding so I was wondering if somebody could help me out.
I want to set a get request from my iphone app to my website and get the information echoed back from the website to my phone.
I have gotten this far but do not know where to go from here. Any help would be much appreciated, thanks!
- (void)myData:(id)sender
{
NSString *DataToBeSent;
sender = [sender stringByReplacingOccurrencesOfString:#"," withString:#"%20"];
[receivedData release];
receivedData = [[NSMutableData alloc] init];
DataToBeSent = [[NSString alloc] initWithFormat:#"http://194.128.xx.xxx/doCalc/getInfo.php?Data=%#",sender];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:dataToBeSent] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
[request setHTTPMethod: #"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
[dataToBeSent release];
}
OLD WAY
- (void)myData:(id)sender
{
NSString *dataToBeSent;
sender = [sender stringByReplacingOccurrencesOfString:#"," withString:#"%20"];
[receivedData release];
receivedData= [[NSMutableData alloc] init];
dataToBeSent= [[NSString alloc] initWithFormat:#"http://194.128.xx.xxx/doCalc/getInfo.php?Data=%#",sender];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:dataToBeSent]];
Theconn= [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
NSLog (#"test1 %#", theRequest);
NSLog (#"test2 %#", Theconn);
[dataToBeSent release];
}
Then the following methods are called and I get my data BUT if I sent another request after my first one but different data on the same connection, it would always give me the same result which shouldn't happen
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
/* appends the new data to the received data */
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
NSString *stringData= [[NSString alloc]
initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Got data? %#", stringData);
[self displayAlertCode:stringData];
[stringData release];
// Do unbelievably cool stuff here //
}
Assuming your data loaded properly you can convert the data into a string and do whatever you want with it.
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
//Make sure to set the correct encoding
NSString* responseString = [[NSString alloc] initWithData:response1 encoding:NSASCIIStringEncoding];
If your server returns JSON there are 3rd party libraries that can parse the string into collections like NSArray and NSDictionary. If your server returns XML then NSXMLParser could be something you can use.
EDIT
I've changed your code to manage the memory a little differently.
.h
#property (nonatomic,retain) NSMutableData * receivedData;
#property (nonatomic,retain) NSURLConnection * Theconn;
.m
#synthesize receivedData;
#synthesize Theconn;
//A bunch of cool stuff
- (void)myData:(id)sender
{
//If you already have a connection running stop the existing one
if(self.Theconn != nil){
[self.Theconn cancel];
}
sender = [sender stringByReplacingOccurrencesOfString:#"," withString:#"%20"];
//This will release your old receivedData and give you a new one
self.receivedData = [[[NSMutableData alloc] init] autorelease];
NSString *dataToBeSent = [NSString stringWithFormat:#"http://194.128.xx.xxx/doCalc/getInfo.php? Data=%#",sender];
NSURLRequest *theRequest= [NSURLRequest requestWithURL:[NSURL URLWithString:dataToBeSent]];
//This will release your old NSURLConnection and give you a new one
self.Theconn = [NSURLConnection connectionWithRequest:theRequest delegate:self];
NSLog (#"test1 %#", theRequest);
NSLog (#"test2 %#", Theconn);
}
//...
//Your delegate methods
//...
- (void) dealloc{
[receivedData release];
[Theconn release];
[super dealloc];
}