對于初入職場的iOS小伙伴們, 搭建UI--大家肯定是沒什么問題了.
而對于網(wǎng)絡請求的POST和GET, 應該還是會有問題;
例如, 如何將APP的token捆綁到請求中, 進行文件的上傳 -- 現(xiàn)在我們就來解決下面兩個問題:
1,如何將token添加到請求頭????? 2, 上傳失敗, 會出現(xiàn)的部分error解決.
問題一: 添加token到請求頭的代碼如下:
NSDictionary *dict =? @{@"name" : @"小明",
@"age" :@"20"
};
//實例化AFHTTPSessionManager
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//調(diào)出請求頭
manager.requestSerializer = [AFJSONRequestSerializer serializer];
//將token封裝入請求頭
[manager.requestSerializer setValue:TOKEN forHTTPHeaderField:@"token-id"];
//post上傳文件
[manager POST:@"http://192.168.0.90/****" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id? _Nullable responseObject) {
NSLog(@"上傳成功 === %@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"上傳錯誤 == error == %@",error);
}];
問題二: 上傳失敗, 有時候會出現(xiàn)如下error:
"error == Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/plain" UserInfo={com.alamofire.serialization.response.error.response={ URL: http://192.168.0.192/api/grey/blood_pressure/upload_data } { status code: 200, headers {
Connection = "keep-alive";
"Content-Type" = "text/plain;charset=UTF-8";
Date = "Fri, 25 Nov 2016 01:05:46 GMT";
Server = "nginx/1.11.5";
"Transfer-Encoding" = Identity;
} }, NSErrorFailingURLKey=http://192.168.0.192/api/grey/blood_pressure/upload_data, com.alamofire.serialization.response.error.data=<7b227265 73756c74 5f636f64 65223a22 30222c22 72657375 6c745f6d 7367223a 22737563 63657373 227d>, NSLocalizedDescription=Request failed: unacceptable content-type: text/plain}"
請不要慌張, 只需要你在AFNetworking的第三方框架內(nèi)找到AFURLResponseSerialization.m 文件
修改第228行代碼, 添加一項@"text/plain", 同時添加@"text/xml"也是在這個地方:
//? ? self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain",@"text/json", @"text/javascript", nil];
通過以上, 接下來就可以成功上傳文件到服務器了.