iOS Get同步與異步

//異步所需要簽訂的協議
@interfaceGetViewController ()<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"

-------------------------------------------------------------------------

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



發佈了32 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章