iOS-GET請求詳細操作-GET佈建要求頭
難得一次備忘相當詳細的原生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];}