難得一次備注相當詳細的原生GET網絡請求操作,強迫症一樣記錄下來和大家分享… 也備復制用
-(void)getResult{
_MB = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
//接口路徑
NSString *path = @"http://a.apix.cn/apixlife/phone/phone";
//路徑-+參數
NSString *pathWithPhoneNum = [NSString stringWithFormat:@"%@?phone=%@",path,_phoneNumFD.text];
//中文編碼
NSString *urlPath = [pathWithPhoneNum stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//URL
NSURL *phoneURL = [NSURL URLWithString:urlPath];
//請求對象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:phoneURL];
//請求方式
[request setHTTPMethod:@"GET"];
//請求頭
[request setValue:@"92b5787ecd17417b718a2aaedc7e6ce8" forHTTPHeaderField:@"apix-key"];
//網絡配置
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//網絡會話
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
//任務
NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//回到主線程更新UI -> 撤銷遮罩
dispatch_async(dispatch_get_main_queue(), ^{
[_MB hide:YES];
});
if (error) {
NSLog(@"請求失敗... %@",error);
//提示用戶請求失敗!
UIAlertController *AV = [UIAlertController alertControllerWithTitle:@"提示" message:@"抱歉,服務器錯誤,請稍後重試..." preferredStyle:UIAlertControllerStyleActionSheet];
[AV addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//點擊OK,進行相應操作,可置nil
NSLog(@"您點擊了OK..");
}]];
[self presentViewController:AV animated:YES completion:nil];
}else{
//JSON 解析 蘋果原生效率最高
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
if ([[result objectForKey:@"message"] isEqualToString:@"success"]) {
//獲取數據->主線程更新UI
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *data = [result objectForKey:@"data"];
NSString *city = [data objectForKey:@"city"];
NSString *province = [data objectForKey:@"province"];
NSString *belong = [NSString stringWithFormat:@"%@ · %@",province,city];
[_resultLB setText:belong];
});
}else{
NSLog(@"未查到信息....");
}
NSLog(@"請求成功... %@",result);
}
}];
//開始任務
[sessionTask resume];
}