您將不得不使用NSURLConnection。這相當簡單,但比NSData方法涉及更多。
首先,創建一個NSURLConnection的:
NSMutableData *receivedData;
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:imgLink]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
receivedData=[[NSMutableData data] retain];
} else {
// inform the user that the download could not be made
}
現在,添加<NSURLConnectionDelegate>到類的頭和實現以下方法:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
第一個應該追加數據,如下所示,最後一個應該創建並顯示圖像。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
{
// append the new data to the receivedData
// receivedData is declared as a method instance elsewhere
[receivedData appendData:data];
}
查看this document瞭解更多詳情。
我希望這聽起來不笨,但是:我已經在同一個類中使用NSURLConnection來處理另一件事了。所以...我怎麼知道委託方法正在被調用時,做一個或其他的事情,並採取相應的行動? – pabloruiz55 2010-01-27 21:42:24
您的委託方法的連接參數將發生更改。 – 2013-08-31 08:06:36