无法使用 Afnetworking 在 SignUp POST 请求中保存图片
Unable to save picture in SignUp POST request with Afnetworking
我正在尝试使用 AFNetworking 通过 Multiparts 在服务器上上传图片。我试图在没有图像的情况下发出一个简单的 POST 请求并且它工作正常。现在,可以说服务 URL 绝对没问题,服务器没有问题,我可以看到保存在文档目录中的图像 URL 也很好,所有其他参数也都很好,因为他们都在处理简单的请求。谁能在我的代码中发现一些错误?我的代码是:
(void)uploadPicture:(NSMutableDictionary *)param
{
NSString *string=[NSString stringWithFormat:@"%@%@",base_url,@"register"];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:string parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:getImagePath] name:@"picture" fileName:getImagePath mimeType:@"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setStringEncoding:NSUTF8StringEncoding];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dic=responseObject;
NSLog(@"");
}
}];
[uploadTask resume];
}
NSString *string=[NSString stringWithFormat:@"%@%@",base_url,@"register"];
@autoreleasepool {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:strurl
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSMutableArray *allKeys = [[imgParameters allKeys] mutableCopy];
for (NSString *key in allKeys) {
id object = [imgParameters objectForKey:key];
int timestamp = [[NSDate date] timeIntervalSince1970];
NSString *str = [[NSString alloc] initWithFormat:@"%d", timestamp];
NSString *ranstrin = [self randomStringWithLength:8];
// if ([key isEqualToString:@"image"]) {
str = [NSString stringWithFormat:@"TestThumb_%d_%@.jpg",
timestamp, ranstrin];
[formData appendPartWithFileData:object
name:key
fileName:str
mimeType:@"image/jpeg"];
}
}
progress:^(NSProgress *_Nonnull uploadProgress) {
}
success:^(NSURLSessionDataTask *_Nonnull task,
id _Nullable responseObject) {
complete(responseObject, nil);
}
failure:^(NSURLSessionDataTask *_Nullable task,
NSError *_Nonnull error) {
complete(nil, error);
}];
试试这个功能:
第一个解决方案
注意:您需要根据需要进行自定义
-(void)getResponeseWithURL:(NSString *)url WithParameter:(NSDictionary *)parameter WithImage:(UIImage *)image ImageArray:(NSMutableArray *)arrImage WithImageParameterName:(NSString *)imagename WithCallback:(void(^)(BOOL success, id responseObject))callback {
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",BASEURL,url] parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (image) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:imagename fileName:@"Image.jpg" mimeType:@"image/jpeg"];
}
else if (arrImage){
int i = 1;
for (UIImage *recipeimage in arrImage) {
// this condition for maintain server side coloum format : ex name , name_2 , name_3
[formData appendPartWithFileData:UIImageJPEGRepresentation(recipeimage, 0.8) name:i == 1 ? imagename : [NSString stringWithFormat:@"%@_%d",imagename,i] fileName:@"Image.jpg" mimeType:@"image/jpeg"];
i++;
}
}
}error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
[UtilityClass showAlertWithMessage: @"Please try again" andWithTitle:@"Network Error" WithAlertStyle:AFAlertStyleFailure];
NSLog(@"Error: %@", [[NSString alloc]initWithData:[[error valueForKey:@"userInfo"] valueForKey:@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding]);
[UtilityClass removeActivityIndicator];
callback(NO,nil);
} else {
callback(YES,responseObject);
}
}];
[uploadTask resume];
}
第二
可能是你忘了在你的项目plist文件中添加ATS所以你需要添加这个.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
我正在尝试使用 AFNetworking 通过 Multiparts 在服务器上上传图片。我试图在没有图像的情况下发出一个简单的 POST 请求并且它工作正常。现在,可以说服务 URL 绝对没问题,服务器没有问题,我可以看到保存在文档目录中的图像 URL 也很好,所有其他参数也都很好,因为他们都在处理简单的请求。谁能在我的代码中发现一些错误?我的代码是:
(void)uploadPicture:(NSMutableDictionary *)param
{
NSString *string=[NSString stringWithFormat:@"%@%@",base_url,@"register"];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:string parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:getImagePath] name:@"picture" fileName:getImagePath mimeType:@"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setStringEncoding:NSUTF8StringEncoding];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dic=responseObject;
NSLog(@"");
}
}];
[uploadTask resume];
}
NSString *string=[NSString stringWithFormat:@"%@%@",base_url,@"register"];
@autoreleasepool {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:strurl
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSMutableArray *allKeys = [[imgParameters allKeys] mutableCopy];
for (NSString *key in allKeys) {
id object = [imgParameters objectForKey:key];
int timestamp = [[NSDate date] timeIntervalSince1970];
NSString *str = [[NSString alloc] initWithFormat:@"%d", timestamp];
NSString *ranstrin = [self randomStringWithLength:8];
// if ([key isEqualToString:@"image"]) {
str = [NSString stringWithFormat:@"TestThumb_%d_%@.jpg",
timestamp, ranstrin];
[formData appendPartWithFileData:object
name:key
fileName:str
mimeType:@"image/jpeg"];
}
}
progress:^(NSProgress *_Nonnull uploadProgress) {
}
success:^(NSURLSessionDataTask *_Nonnull task,
id _Nullable responseObject) {
complete(responseObject, nil);
}
failure:^(NSURLSessionDataTask *_Nullable task,
NSError *_Nonnull error) {
complete(nil, error);
}];
试试这个功能:
第一个解决方案
注意:您需要根据需要进行自定义
-(void)getResponeseWithURL:(NSString *)url WithParameter:(NSDictionary *)parameter WithImage:(UIImage *)image ImageArray:(NSMutableArray *)arrImage WithImageParameterName:(NSString *)imagename WithCallback:(void(^)(BOOL success, id responseObject))callback {
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",BASEURL,url] parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (image) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:imagename fileName:@"Image.jpg" mimeType:@"image/jpeg"];
}
else if (arrImage){
int i = 1;
for (UIImage *recipeimage in arrImage) {
// this condition for maintain server side coloum format : ex name , name_2 , name_3
[formData appendPartWithFileData:UIImageJPEGRepresentation(recipeimage, 0.8) name:i == 1 ? imagename : [NSString stringWithFormat:@"%@_%d",imagename,i] fileName:@"Image.jpg" mimeType:@"image/jpeg"];
i++;
}
}
}error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
[UtilityClass showAlertWithMessage: @"Please try again" andWithTitle:@"Network Error" WithAlertStyle:AFAlertStyleFailure];
NSLog(@"Error: %@", [[NSString alloc]initWithData:[[error valueForKey:@"userInfo"] valueForKey:@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding]);
[UtilityClass removeActivityIndicator];
callback(NO,nil);
} else {
callback(YES,responseObject);
}
}];
[uploadTask resume];
}
第二
可能是你忘了在你的项目plist文件中添加ATS所以你需要添加这个.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>