使用URLSession实现网络请求
2018-03-15 本文已影响0人
叶神游戏
//下载搜索全文数据
NSString *string=[NSString stringWithFormat:@"%@Ajax/AjaxSearchBook.ashx?BookId=%@&No=0&SearchContent=%@",PhoneUrl,self.bookModel.BookID,searchBar.text];
NSString *urlString=[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url=[NSURL URLWithString:urlString];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
delegate:self
delegateQueued];;
NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSArray *array=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if (array.count>0)
{
[searchDataArray removeAllObjects];
for (NSDictionary *dic in array)
{
[searchDataArray addObject:dic];
}
//回到主线程
dispatch_async(dispatch_get_main_queue(), ^{
isSeacrhAll=YES;
[searchTableView reloadData];
});
}
}];
//执行下载
[dataTask resume];