使用步驟
- 創建一個URL
- 創建請求
- 發送請求
解析數據
iOS9.0 之後,開始需要網絡權限,而不是XCode7.0 ,因爲XCode7.0默認是9.0的項目,如果改成8.0的項目就美問題了
事例代碼
- (void)loadData
{
//1.創建 URL
NSURL* url = [NSURL URLWithString:@"http://localhost/demo.json"];
//2.創建請求
NSURLRequest* request = [NSURLRequest requestWithURL:url];
//3.創建連接併發送異步請求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse* _Nullable response, NSData* _Nullable data, NSError* _Nullable connectionError) {
if (connectionError == nil) {
//4.解析數據
JSONDecoder* decoder = [JSONDecoder decoder];
id jsonString = [decoder objectWithData:data];
NSLog(@"%@", jsonString);
}
}];
}