Use Apple recommended NSURL delegate methods

和自甴很熟 提交于 2020-01-07 02:44:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!