2013-03-03 22 views
0

The answer to my original question使用以下代碼。使用Apple推薦的NSURL代理方法

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){...}]; 

我原來的代碼沒有工作,但如下。我的代碼使用了Apple Docs中建議的一組委託方法(connection:didReceiveResponse:,connection:didReceiveData:,connection:didFailWithError:and connectionDidFinishLoading :)。

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."); 
     }; 

委託方法是否與建議的代碼兼容,如果是,我如何將它們集成到建議的代碼中?

回答

3

您可以使用一個或另一個。

問題中的第一位代碼不使用任何委託方法。相反,你在完成處理程序中做所有事情。您要麼收到數據,要麼收到錯誤。您不需要處理追加數據或處理重定向。

如果你需要更多的控制,那麼你必須使用舊的形式以及適當的委託方法。

完成處理程序版本要簡單得多,應該使用,除非您需要委託版本的靈活性。

相關問題