我正在尝试通过 AFHTTPRequestOperation
将照片上传到我的网络服务器。这是我的 AFHTTPSessionManager
。通过此 manager
的所有 http 请求都完美无缺。
- (AFHTTPSessionManager *)manager
{
if (_manager == nil) {
_manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"https://my.domain.com/api/v2"]];
[_manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"username" password:@"password"];
AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
policy.allowInvalidCertificates = YES;
_manager.securityPolicy = policy;
}
return _manager;
}
但是当我尝试上传带有进度处理的照片时:
- (void)photoSend:(UIImage *)photo
toUsers:(NSArray *)users
completion:(CompletionHandler)completion
progress:(ProgressionHandler)progress
{
NSDictionary *params = @{
@"token":self.token,
@"to_usernames":[users componentsJoinedByString:@","],
};
NSString *urlString = [[NSURL URLWithString:@"photo/send" relativeToURL:self.manager.baseURL] absoluteString];
NSMutableURLRequest *request = [self.manager.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:params constructingBodyWithBlock:^(id <AFMultipartFormData> formData)
{
[formData appendPartWithFileData:UIImageJPEGRepresentation(photo,0.8)
name:@"photo"
fileName:@"image.jpg"
mimeType:@"image/jpg"];
} error:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
// Following 2 lines does not make sense. Http headers contains auth data without this code
//NSURLCredential *credential = [NSURLCredential credentialWithUser:@"login" password:@"password" persistence:NSURLCredentialPersistenceNone];
//[operation setCredential:credential];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
progress(totalBytesWritten*1.0/totalBytesExpectedToWrite);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
completion(operation.response, responseObject, operation.error);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
completion(operation.response, nil, error);
}];
[self.manager.operationQueue addOperation:operation];
}
我收到以下错误:
最佳答案
这是解决方案:
AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
policy.allowInvalidCertificates = YES;
operation.securityPolicy = policy;
因此,HTTP 基本身份验证数据由管理器提供给操作,但 SSL 策略不是。