NSURLRequest詳解

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.