URLRequest 的一個執行個體
// Create the request.//所構建的NSURLRequest具有一個依賴於緩衝響應的特定策略,cachePolicy取得策略,timeoutInterval取得逾時值NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];// create the connection with the request// and start loading the dataNSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];if (theConnection) { // Create the NSMutableData to hold the received data. // receivedData is an instance variable declared elsewhere. receivedData = [[NSMutableData data] retain];} else { // Inform the user that the connection failed.}
其中:NSURLRequest預設的cache policy是NSURLRequestUseProtocolCachePolicy, 是最能保持一致性的協議。NSURLRequestReloadIgnoringCacheData 忽略緩衝直接從原始地址下載NSURLRequestReturnCacheDataElseLoad 只有在cache中不存在data時才從原始地址下載NSURLRequestReturnCacheDataDontLoad 允許app確定是否要返回cache資料,如果使用這種協議當本地不存在response的時候,建立NSURLConnection or NSURLDownload執行個體時將會馬上返回nil;這類似於離線模式,沒有建立網路連接;
你只需要實現以下delegate方法來處理資料響應
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
NSURLConnect還提供了一個方便的類方法(class method) : sendSynchronousRequest:returningResponse:error:可用來 同步地載入一個URL請求
+ (NSData *)sendSynchronousRequest: (NSURLRequest *)request returningResponse: (NSURLResponse **)response error: (NSError **)error
- request 要裝載的URL請求. 這個request 對象 作為初始化進程的一部分,被深度複製(deep-copied). 在這個方法返回之後, 再修改request, 將不會影響用在裝載的過程中的request
- reponse 輸出參數, 由伺服器返回的URL響應
- error 輸出參數, 如果在處理請求的過程中發生錯誤,就會使用. 無錯誤,就為NULL
一個實現非同步get請求的例子:
NSString *url = [NSString stringWithFormat:@"http://localhost/chat/messages.php?past=%ld&t=%ld", lastId, time(0) ];NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];[request setURL:[NSURL URLWithString:url]];[request setHTTPMethod:@"GET"]; NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self]; if (conn) { receivedData = [[NSMutableData data] retain]; } else { } - (void)timerCallback {//[timer release];[self getNewMessages];}- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [receivedData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [receivedData appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { if (chatParser) [chatParser release];if ( messages == nil )messages = [[NSMutableArray alloc] init];chatParser = [[NSXMLParser alloc] initWithData:receivedData];[chatParser setDelegate:self];//set the delegate[chatParser parse];//start parse[receivedData release]; [messageList reloadData];NSInvocation *invocation = [NSInvocation invocationWithMethodSignature: [self methodSignatureForSelector: @selector(timerCallback)]];[invocation setTarget:self];[invocation setSelector:@selector(timerCallback)];//timer = [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO]; [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO];//if set yes,then very 5 seconds updata the table}
一個實現同步Get請求的例子:
// 初始化請求 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; // 設定URL [request setURL:[NSURL URLWithString:urlStr]]; // 設定HTTP方法 [request setHTTPMethod:@"GET"]; // 發 送同步請求, 這裡得returnData就是返回得資料了 NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; // 釋放對象 [request release];
更多詳細資料請參見蘋果開發文檔:http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html