问题
In my application I want to use the NSURLConnection class. So please tell me how to use this one? This contain the lot of delegate methods, please tell me how to use them?
回答1:
Initiate the connection using
self.responseData = [NSMutableData data];
NSURL *url = [NSURL URLWithString:@"http://sampleurl/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection autorelease];
and you can catch the response in the connectionDidFinishLoading delegate method
#pragma mark - NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Connection failed: %@", [error description]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//Getting your response string
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
}
For your memory leak problem
Declare the response data in interface file
NSMutableData *_responseData;
with property as below
@property (nonatomic, retain) NSMutableData *responseData;
and synthesize it
@synthesize responseData = _responseData;
Dont release it anywhere (We have used convenient constructors for allocation). We have already set it to nil in connectionDidFinishLoading method.
回答2:
In iOS 5 and OS X 10.7 or later you can load data asynchronously using the following:
NSURL *url = [NSURL URLWithString:@"http://sampleurl/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue]
completionHandler: ^(NSURLResponse * response, NSData * data, NSError * error) {
NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse*)response;
if(httpResponse.statusCode == 200) {
//your code to handle the data
}
}
];
Or if you want to do it synchronously (not recommended if you are loading large data as it will hang the application) (available in OS X 10.2+ and iOS 2.0+)
NSURL *url = [NSURL URLWithString:@"http://sampleurl/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLResponse * response;
NSError * error;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
来源:https://stackoverflow.com/questions/7483085/how-to-use-the-nsurlconnection-for-getting-the-data-from-web