Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a string from an NSURLRequest

Is anybody able to help me get a string returned from an NSURLRequest on an iPhone app? I have to send some user credentials to a URL and it will return a customer ID number. That is what I need to be pulled in as a string, I am not used to doing working with servers or HTTP requests, so any help will be great. I have already read the Apple Docs about it and am a bit lost on this part.

like image 509
Tanner Ewing Avatar asked Apr 25 '12 19:04

Tanner Ewing


1 Answers

This is a standard pattern async downloader:

In .h file:

NSMutableData *responseData;

And .m file:

-(void) execute {
    NSString *urlString = @"http://www.google.com";
    responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

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

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

-(void) connectionDidFinishLoading:(NSURLConnection *)connection{
    [connection release];
    NSString *data = [[[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding] autorelease];
    NSLog(@"%@", data);
    [responseData release];
}

This will download Google and outprint the content.

like image 149
Nic Avatar answered Nov 06 '22 21:11

Nic