iOS網絡編程:三、GET代理方式進行異步請求

@interface RootViewController ()<NSURLConnectionDataDelegate>
@property (nonatomic, strong) NSMutableArray *data;
@property (nonatomic, strong) NSMutableData *tempData;
@end


- (void)GetDelegateAction{
    //1 創建URL對象
    NSURL *url = [NSURL URLWithString:CQGETUEL];
    //2 創建URLRequest對象
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    // 3注意!!:同步和異步的不同
    [NSURLConnection connectionWithRequest:request delegate:self];
}
//當收到服務器響應的時候
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    //初始化結構數組
    self.data = [NSMutableArray array];
    //初始化緩衝水桶
    self.tempData = [NSMutableData data];
}
//接收數據
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    //將讀取的部分拼接到水桶中;
    [self.tempData appendData:data];
}
    //當所有數據接收完畢的時候
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
   //對水桶的所有數據進行解析
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.tempData options:NSJSONReadingAllowFragments error:nil];
    NSArray *arr = dict[@"news"];
    for (NSDictionary *dic in arr) {
        News *news = [[News alloc] init];
        [news setValuesForKeysWithDictionary:dic];
        [self.data addObject:news];
    }

}

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