天天看點

iOS Get同步與異步

//異步所需要簽訂的協定 @interface GetViewController ()< NSURLConnectionDelegate , NSURLConnectionDataDelegate >

// 聲明一個連結屬性,主要用是在頁面銷毀但加載還沒完成的時候,在dealloc上終止用的 @property ( nonatomic , retain ) NSURLConnection *connection;

// 聲明一個可變的 data 用于擷取到完整的 data;,注意在那裡初始化 @property ( nonatomic , retain ) NSMutableData *receiveData;

- (void)dealloc

{

    //注意:當這個頁面被銷毀的時候如果請求還沒有完成需要終止這個連結

    [_connectioncancel];

    [_connectionrelease];

    [superdealloc]; } -----------------------------------------------------------------------

#define kSearchURL @"http://api.map.baidu.com/place/v2/search?query=公廁&region=上海&output=json&ak=6E823f587c95f0148c19993539b99295"

#define kNewsListURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"

#define kNewsListParam @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213"

#define kImageURL @ "http://image.zcool.com.cn/56/13/1308200901454.jpg" -------------------------------------------------------------------------

get同步 // 如果有中文轉化一下編碼格式     NSString *newStr = [kSearchURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSetURLFragmentAllowedCharacterSet]];

//把字元串的網址轉化成網址對象

    NSURL *url = [NSURLURLWithString:newStr];

    //建立一個請求

    //timeoutInterval請求逾時的時間 秒為機關

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:urlcachePolicy:(NSURLRequestUseProtocolCachePolicy)timeoutInterval:10];

    //設定一個請求辨別     [request setHTTPMethod:@"Get"];      //利用這個請求 建立一個連結

    NSError *error = nil;

    //建立空的,伺服器響應資訊

    NSURLResponse *response = nil;

    //建立同步連結并得到傳回的資料(data)     NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

   //解析資料

    NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];

    NSLog(@"%@",dataDic);

    NSLog(@"%@",response);

    NSLog(@"%@",data); ------------------------------------------------------------------------ //get異步請求

    //擷取網址對象 (有中文 需要轉碼)

    NSString *urlStr = [kSearchURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];

    //利用網址建立網址對象

    NSURL *url = [NSURL URLWithString:urlStr];

    //利用網址對象建立一個請求

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10];

    //辨別請求類型

    //注意:加辨別符     [request setHTTPMethod:@"Get"]; ------------------------------------------------------- #pragma mark -- block異步連結方法     [NSOperationQueue mainQueue]    代表回到主線程     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {                // 當資料請求完成的時候 會指定這個 block         NSLog(@"%@",data);         // 判斷是否在主線程         NSLog(@"%d",[NSThread isMainThread]);             }];     -------------------------------------------------------------------    

#pragma mark -- 代理方法異步連結

    //利用請求建立一個異步連結

    self.connection = [NSURLConnection connectionWithRequest:requestdelegate:self];

    //開始連結

    [self.connectionstart]; ---------------------------------------------------------------------     #pragma mark --代理方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    //連結成功時建立data

    self.receiveData = [NSMutableData data];

    NSLog(@"已經接收到伺服器的響應資訊,說明連結成功");

    NSLog(@"%@",response);

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    //多次觸發這個方法才能接收到完整的data

    //是以這個時候需要拼接一下data

    //拼接data

    [self.receiveData appendData:data];

    NSLog(@"接收到資料觸發的方法");

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@"%@",self.receiveData);

    //解析資料

    NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:self.receiveData options:(NSJSONReadingMutableContainers)error:nil];

    NSLog(@"%@",dataDic);

    //如果在tableView上展示的話

    //注意:要重新整理界面

    NSLog(@"已經完成資料加載觸發的方法");

}

//請求失敗時觸發

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"請求失敗時觸發 %@",error); }

UI第十六天  16-NSURLRequest

繼續閱讀