IOS ---網路非同步請求

來源:互聯網
上載者:User

標籤:ios   網路   非同步請求   

非同步請求使用與同步和隊列式非同步請求相同的對象,只不過又增加了另一個對象,即NSURLConnectionDelegate:
上代碼:

#import "ViewController.h"NSInteger totalDownLoaded = 0;@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    NSURL *url = [NSURL URLWithString:@"http://www.example.com/test.php"];    NSURLRequest *request = [NSURLRequest requestWithURL:url];    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];    [conn start];}/* *如果協議處理器接收到來自伺服器的重新導向請求,就會調用該方法 */-(NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response{//    NSLog(@"All Headers = %@", [(NSHTTPURLResponse *) response allHeaderFields]);    return  request;}/* *當協議處理器接收到足夠的資料來建立URL響應對象時會調用didReceiveResponse方法。如果在接收到足夠的資料來構建對象前出現了錯誤, *就不會調用該方法 */-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;    NSLog(@"All Headers = %@", [httpResponse allHeaderFields]);    NSLog(@"statusCode = %ld", (long)httpResponse.statusCode);    if (httpResponse.statusCode != 200) {        [connection cancel];        return;    }}/* *當協議處理器接收到部分或全部響應體時會調用該方法。該方法可能不會調用,也可能調用多次,並且調用總是跟在最初的connection:didReceiveResponse之後 */-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{    totalDownLoaded += [data length];    NSLog(@"%ld", (long)totalDownLoaded);}/* *當串連失敗時會調用這個委託方法。該方法可能會在請求處理的任何階段得到調用 */-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{    NSLog(@"netWork connect error");}/* *當整個請求完成載入並且接收到的所有資料都被傳遞給委託後,就會調用該委託方法 */-(void)connectionDidFinishLoading:(NSURLConnection *)connection{    NSLog(@"Finish");}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

IOS ---網路非同步請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.