问题
The answer to my original question uses the following code.
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:self.urlNameInput.text] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *connection, NSData *data, NSError *error){...}];
My original code did not work, but was as follows. My code used a set of delegate methods ( connection:didReceiveResponse:, connection:didReceiveData:, connection:didFailWithError: and connectionDidFinishLoading:) suggested in Apple Docs.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlNameInput.text] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
receivedData = [NSMutableData data] ;
} else {
// Inform the user that the connection failed.
NSLog(@"Their is an error with that URL.");
};
Are the delegate methods compatible with the suggested code, and if so, how can I integrate them into the suggested code?
回答1:
You either use one or the other.
The first bit of code in your question does not use any delegate methods. Instead, you do everything in the completion handler. You either get the data or you get an error. You don't need to deal with appending data or processing redirects.
If you need more control then you must use the older form along with the proper set of delegate methods.
The completion handler version is much simpler and should be used unless you need the flexibility of the delegate version.
来源:https://stackoverflow.com/questions/15181633/use-apple-recommended-nsurl-delegate-methods