警告离题答案
但在某些情况下,您可以决定无法使用 AFNetworking。我的任务只是从自定义 API 下载文件。对于访问,我将"x-token"
在标头中的键上使用令牌。AFNetworking 不仅仅适用于下载,在 GET/POST 请求中一切都很棒!
// we use "x-token" to acces
self.tokenSessionManager = [AFHTTPSessionManager manager];
((AFJSONResponseSerializer *)_tokenSessionManager.responseSerializer).removesKeysWithNullValues = YES;
[_tokenSessionManager.requestSerializer setValue:self.user.token forHTTPHeaderField:@"x-token"];
// it works perfect in other GET/POST requests but not in downloading
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:item.urlString]];
// try to set it directly in request
NSString *key = @"x-token";
[request setValue:[self.tokenSessionManager.requestSerializer valueForHTTPHeaderField:key] forHTTPHeaderField:key];
[[self.tokenSessionManager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
return [NSURL URLWithString:filePath];
} completionHandler:^(NSURLResponse *response, NSURL *urlPath, NSError *error) {
NSLog(@"Failure");
}] resume];
你可以尝试使用NSURLSession
和NSURLRequest
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSString *key = @"x-token";
sessionConfiguration.HTTPAdditionalHeaders = @{key:[self.tokenSessionManager.requestSerializer valueForHTTPHeaderField:key]};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:item.urlString]];
[[session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"Success");
}] resume];