[iOS]通过AFNetworking上传图片到阿里云OSS
2019-01-21 本文已影响60人
雨影
URL链接需要的key和token需要后台事先给你们拼好返回
+ (__kindof NSURLSessionTask *)uploadImagesToOSSWithURL:(NSString *)URL
image:(UIImage *)image
progress:(PPHttpProgress)progress
success:(PPHttpRequestSuccess)success
failure:(PPHttpRequestFailed)failure {
NSData *imageData = UIImageJPEGRepresentation(image, 1);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL]];
request.HTTPMethod = @"PUT";
[request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
NSURLSessionTask *uploadTask = [_sessionManager uploadTaskWithRequest:request
fromData:imageData
progress:^(NSProgress *_Nonnull uploadProgress) {
//上传进度
dispatch_sync(dispatch_get_main_queue(), ^{
progress ? progress(uploadProgress) : nil;
});
}
completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject, NSError *_Nullable error) {
if (!error) {
success(nil, nil);
} else {
[self handelFailuerWith:nil error:error failure:failure];
}
}];
[uploadTask resume];
return uploadTask;
}