異步請求網絡代碼(一)

//
//  ViewController.m
//  01-網絡請求
//
//  Created by jerry on 15/9/24.
//  Copyright (c) 2015年 jerry. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    // 1.url
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/demo.json"];
    // 2.創建請求
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    /**
     *  requestWithURL:url,資源路徑
     *  cachePolicy:緩存策略 
     
     NSURLRequestUseProtocolCachePolicy = 0,  // 默認緩存策略,會自動緩存。
     
     NSURLRequestReloadIgnoringLocalCacheData = 1, // Reload 刷新  Ignoring 忽略 Local 本地CacheData 緩存數據    總體就是忽略本地緩存數據,每次都須要從服務器獲取數據.
     // 兩個都是用來作離線訪問的。通常配合reachablility(蘋果提供的檢測網絡鏈接框架)配合使用。
     // 若是用戶使用wifi  就使用這個策略(國內通常都使用這個策略無論是否是wifi 仍是3g)
     NSURLRequestReturnCacheDataElseLoad = 2, // 若是有緩存,就用緩存,若是沒有就上網加載 (hot  用的比較多)
     // 若是用戶使用3g 網絡,使用這個策略
     NSURLRequestReturnCacheDataDontLoad = 3, // 若是沒有緩存,就緩存,若是沒有緩存就返回空。 (hot 用的比較多)
     
     
     *  timeoutInterval:超時時間,默認是60s   通常設置15~20,超過這個時間之後,服務器尚未響應就不繼續等待 。
     *  SDWebImage 超時時長,設置的事15s 。
     *  AFN 超時時長 60s。
     */
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15];
    
    // 3. 發送請求
    /**
     sendAsynchronousRequest:request 參數
     queue:隊列,這個隊列完成後,回調block執行隊列。
       Asynchronous:只要是異步,確定會開新的線程。
     
     // 使用場景:若是下載的事壓縮包。解壓縮也是一個耗時操做。
     若是回調block裏面只須要更新ui 那麼就能夠在開始就制定queue爲主隊列。
     handler:網絡訪問完成之後執行的代碼塊。
     response:服務器的響應(包含響應行/響應頭。。。通常不關心這個東西,只有在下載的時候纔會關心這個操做)
     data:服務器返回的二進制數據
     connectionError:服務器返回的錯誤信息,只要是有網絡訪問,就會有可能有錯誤。
     */
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError || data == nil) { // 若是爲真,說明有錯誤
            NSLog(@"網絡不給力,請稍後再試。。。");
            NSLog(@"%@",connectionError);
            return ;
        }
        NSLog(@"解壓縮。。%@",[NSThread currentThread]);
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"更新ui ");
             NSLog(@"%@", [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        });
       
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

報錯。。。。html

2015-09-24 15:50:12.779 01-網絡請求[839:20612] 解壓縮。。<NSThread: 0x7fa171c47cd0>{number = 3, name = (null)}
2015-09-24 15:50:12.836 01-網絡請求[839:20542] 更新ui 
2015-09-24 15:50:12.836 01-網絡請求[839:20542] <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /demo.json was not found on this server.</p>
</body></html>
相關文章
相關標籤/搜索