tags:

views:

21

answers:

2

Hi,

I try to build an app for user that enter his data and this data will be post to a webserver for save in a Database. This web server returns some data back like Id or something else. How I can receive the data the webserver returns back? The transfer works already with NSMutableURLRequest. But I search for a sollution to read the answer from the web server and display it on a label.

A: 

Have a look at the delegate methods of NSURLConnection.

tob
A: 

Example of how it could be done. Original source

NSString *post = @"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.someurl.com"]];
[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) 
{
    receivedData = [[NSMutableData data] retain];
} 
else 
{
    // inform the user that the download could not be made
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    NSString *aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
    NSLog(aStr);

    // release the connection, and the data object
    [receivedData release];
}
willcodejavaforfood