Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to return data gotten from a web service in objective- c (iPhone)?
    text
    copied!<p>This might be a dumb question. Sorry if it is.</p> <p>But Im working on a project that consumes web services. I can connect to the web service and get the data I need fine.</p> <p>I would like to have a method that returns this data obtained from the web service to the caller. The only problem is that the data is only obtained inside the ConnectionDidFinishLoading method, and I can't access this data from my method.</p> <p>here is my code, that works fine:</p> <pre><code>- (NSData *) dataForMethod:(NSString *)webMethod withPostString:(NSString *)postString { NSURL *url = [NSURL URLWithString:[SigameWebServiceAddress stringByAppendingFormat:@"%@%@", @"/", webMethod]]; NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]]; [req addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [req addValue:msgLength forHTTPHeaderField:@"Content-Length"]; [req setHTTPMethod:@"POST"]; [req setHTTPBody: [postString dataUsingEncoding:NSUTF8StringEncoding]]; conn = [[NSURLConnection alloc] initWithRequest:req delegate:self]; if (conn) { webData = [NSMutableData data]; } // I WOULD LIKE TO RETURN WEBDATA TO THE CALLER HERE, BUT WEBDATA IS EMPTY NOW, THE //connectionDidFinishLoading ONLY GETS CALLED WITH THE DATA I WANT AFTER THE COMPILER //IS DONE EXECUTING MY METHOD. } -(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 { NSLog(@"FATAL ERROR"); } -(void) connectionDidFinishLoading:(NSURLConnection *) connection { NSLog(@"DONE. Received Bytes: %d", [webData length]); NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; //---shows the XML--- NSLog(@"%@", theXML); //NOW, THIS IS THE DATA I WANT. BUT HOW CAN I RETURN THIS TO //THE CALLER. I MEAN, THE CALLER THAT CALLED MY METHOD //+ (NSData *) dataForMethod: withPostString: } </code></pre> <p>Any help here is appreciated! Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload