简体   繁体   English

使用AFNetworking 3.0上传图像

[英]Uploading an image using AFNetworking 3.0

I tried to upload the image with using AFNetworking3.0. 我尝试使用AFNetworking3.0上传图像。 I have tried to find how to upload image from all stackoverflow and tutorial, but all of these are relative with AFNetworking2.0 and below. 我试图找到如何从所有stackoverflow和教程中上传图像,但是所有这些都与AFNetworking2.0及以下版本有关。 The main focus is that I am going to upload the image to the web site. 主要重点是我将图像上载到网站。

Once the image is uploaded, the image url should be existed on web site. 图片上传后,图片网址应存在于网站上。

Please see the code below. 请参见下面的代码。

AFHTTPRequestOperationManager *requestManager;

[requestManager POST:KAPIUploadOutfit parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 
{
        [formData appendPartWithFileURL:fileURL name:@"photo_url" fileName:filename mimeType:@"image/png" error:nil];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        successCB(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        errorCB(CONNECTION_ERROR);
    }];

I am not sure what the parameter is about. 我不确定该参数是关于什么的。 Please tell me how to do it. 请告诉我该怎么做。

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

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
                  [progressView setProgress:uploadProgress.fractionCompleted];
              });
          }
          completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
              if (error) {
                  NSLog(@"Error: %@", error);
              } else {
                  NSLog(@"%@ %@", response, responseObject);
              }
          }];

[uploadTask resume];

In this code http://example.com/upload is api where image is going to upload and file://path/to/image.jpg is your local image path. 在此代码中, http://example.com/upload是要上传图片的api,而file://path/to/image.jpg是您的本地图片路径。

In AFNetworking 3.0 upload task works like this. 在AFNetworking 3.0中,上传任务的工作原理如下。

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
    } error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

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
                      [progressView setProgress:uploadProgress.fractionCompleted];
                  });
              }
              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                  if (error) {
                      NSLog(@"Error: %@", error);
                  } else {
                      NSLog(@"%@ %@", response, responseObject);
                  }
              }];

[uploadTask resume];

For complete guide please check AFNetworking Guide . 有关完整的指南,请查看《 AFNetworking指南》 I hope it will resolve your problem. 希望它能解决您的问题。

If we want to call API(using AFNetworking 3.0) for upload images and videos with parameter using same request that time I think would be best class for me 如果我们想调用API(使用AFNetworking 3.0)以使用相同的请求上传带有参数的图片和视频,那我认为这对我来说是最好的选择

    #import <Foundation/Foundation.h>
    #import "MBProgressHUD.h"
    #import "AFNetworking.h"


    @protocol WebServiceDelegate <NSObject>

    @required
    -(void)webserviceCallFinishedWithSuccess:(BOOL)success andResponseObject:(id)responseObj andError:(NSError *)error forWebServiceTag:(NSString *)tagStr;
    @end

    @interface WebService : NSObject<MBProgressHUDDelegate>
    {
        MBProgressHUD   *mbProcess;
        UIView          *view_Process;
    }
    @property(nonatomic, retain)id <WebServiceDelegate> delegate;
    + ( WebService* ) sharedManager;
    -(void)showProgressHUD;
    -(void)dismissProgressHUD;
    -(void)showProgressHUDWithSuccess;
    -(id)initWithView:(UIView *)view andDelegate:(id <WebServiceDelegate>)del;
    -(void)callWebserviceWithParams:(NSMutableDictionary*)_params
                             action:(NSString*)_action
                        withLoading:(BOOL)loading
                            success:(void(^)(id _responseObject))_success
                            failure:(void(^)(NSError* _error))_failure;


    -(void)PafortRequestWithParams:(NSMutableDictionary*)_params
                            action:(NSString*)_action
                       withLoading:(BOOL)loading
                           success:(void(^)(id _responseObject))_success
                           failure:(void(^)(NSError* _error))_failure;


    -(void)callWebserviceToUploadImageWithParams:(NSMutableDictionary *)_params
                                       imgParams:(NSMutableDictionary *)_imgParams
                                      videoParms:(NSMutableDictionary *)_videoParams
                                          action:(NSString *)_action
                                     withLoading:(BOOL)loading
                                         success:(void (^)(id _responseObject))_success
                                         failure:(void (^)(NSError * _error))_failure;


    @end


// This is .m class 
    #import "WebService.h"
    #import "ProgressHUD.h"
    @implementation WebService
    @synthesize delegate;

    -(id)initWithView:(UIView *)view andDelegate:(id <WebServiceDelegate>)del
    {
        self = [super init];

        if(self)
        {
            view_Process = view;
            self.delegate = del;
        }
        return self;
    }
    + ( WebService* ) sharedManager
    {
        __strong static WebService* sharedObject = nil ;
        static dispatch_once_t onceToken ;

        dispatch_once( &onceToken, ^{
            sharedObject = [ [ WebService alloc ] init ] ;
        } ) ;
        return sharedObject ;
    }

    -(void)showProgressHUD{
        [theAppDelegate.window endEditing:YES];

        [ProgressHUD hudColor:THEME_BLACK_COLOR];
        [ProgressHUD backgroundColor:[UIColor colorWithWhite:0.0 alpha:0.1]];
        [ProgressHUD statusColor:WHITE_COLOR];

        [ProgressHUD hudColor:THEME_BLACK_COLOR];
        [ProgressHUD spinnerColor:WHITE_COLOR];

        [ProgressHUD show:LocalizedString(@"Please Wait") Interaction:NO];
    }
    -(void)showProgressHUDWithSuccess{
        [theAppDelegate.window endEditing:YES];

        [ProgressHUD hudColor:THEME_BLACK_COLOR];
        [ProgressHUD backgroundColor:[UIColor colorWithWhite:0.0 alpha:0.1]];
        [ProgressHUD statusColor:WHITE_COLOR];

        [ProgressHUD hudColor:THEME_BLACK_COLOR];
        [ProgressHUD spinnerColor:WHITE_COLOR];

        [ProgressHUD showSuccess:LocalizedString(@"Success!")];
    }
    -(void)dismissProgressHUD{
        [ProgressHUD dismiss];
    }
    -(void)callWebserviceWithParams:(NSMutableDictionary*)_params
                             action:(NSString*)_action
                        withLoading:(BOOL)loading
                            success:(void(^)(id _responseObject))_success
                            failure:(void(^)(NSError* _error))_failure
    {

        if(loading)
        {
            [self showProgressHUD];
        }

        NSString *url = BASE_URL;//[BASE_URL stringByAppendingString:_action];
        [_params setValue:_action forKey:@"method"];
        [_params setValue:[[SingletonClass sharedManager] get_user_id] forKey:PM_USER_ID];
        [_params setValue:PM_USER forKey:PM_USER_TYPE];
        [_params setValue:@"1" forKey:@"device_type"];


        DLog(@"API:>>> %@",url);
        DLog(@"PARAMS:>>>%@",_params);
        AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];

        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/jsvascript",@"text/html", nil];

        [manager POST:url parameters:_params progress:^(NSProgress * _Nonnull uploadProgress) {

        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if(loading)
            {
                [ProgressHUD dismiss];
            }
            DLog(@"Response : >>> %@",responseObject);

            if ([[responseObject valueForKey:RESPONSE_STATUS] intValue] == 1) {
                if (_success) {
                    _success (responseObject);
                }
            }else{
                if(loading)
                {
                    showAlertWithErrorMessage([responseObject valueForKey:RESPONSE_MESSAGE]);
                }
                NSError *error;
                if (_failure) {
                    _failure (error);
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            DLog(@"Error = %@",[error localizedDescription]);
            if(loading)
            {
                [ProgressHUD dismiss];
                [self showFailureMessage:error];

            }

            if (_failure) {
                _failure (error);
            }
        }];

    }


    -(void)showFailureMessage:(NSError*)error{
        if ([[error description] rangeOfString:@"The request timed out."].location != NSNotFound)
        {
            showAlertWithErrorMessage(@"The request timed out, please verify your internet connection and try again.");
        }
        else if ([[error description] rangeOfString:@"The server can not find the requested page"].location != NSNotFound || [[error description] rangeOfString:@"A server with the specified hostname could not be found."].location != NSNotFound)
        {
            showAlertWithErrorMessage(@"Unable to reach to the server, please try again after few minutes");
        }
        else if([[error description] rangeOfString:@"The network connection was lost."].location != NSNotFound)
        {
            showAlertWithErrorMessage(@"The network connection was lost, please try again.");

        }
        else if([[error description] rangeOfString:@"The Internet connection appears to be offline."].location != NSNotFound)
        {
            showAlertWithErrorMessage(@"The Internet connection appears to be offline.");

        }
        else if([[error description] rangeOfString:@"JSON text did not start with array or object and option to allow fragments not set."].location != NSNotFound)
        {
            showAlertWithErrorMessage(@"Server error!");
        }
        else
        {
            showAlertWithErrorMessage(@"Unable to connect, please try again!");

        }
    }

    -(void)callWebserviceToUploadImageWithParams:(NSMutableDictionary *)_params
                                       imgParams:(NSMutableDictionary *)_imgParams
                                      videoParms:(NSMutableDictionary *)_videoParams
                                          action:(NSString *)_action
                                     withLoading:(BOOL)loading
                                         success:(void (^)(id _responseObject))_success
                                         failure:(void (^)(NSError * _error))_failure{

        if(loading)
        {

            [self showProgressHUD];

        }

        NSString *urlString = BASE_URL;//[BASE_URL stringByAppendingString:_action];
        [_params setValue:_action forKey:@"method"];
        [_params setValue:[[SingletonClass sharedManager] get_user_id] forKey:PM_USER_ID];
        [_params setValue:PM_USER forKey:PM_USER_TYPE];
        [_params setValue:@"1" forKey:@"device_type"];

        DLog(@"API:>>> %@",urlString);
        DLog(@"PARAMS:>>>%@",_params);

        NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] init];
        [urlRequest setURL:[NSURL URLWithString:urlString]];
        [urlRequest setHTTPMethod:@"POST"];
        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [urlRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];

        // [urlRequest setValue:contentType forHTTPHeaderField:@"Content-type: application/json"]
        NSMutableData *body = [NSMutableData data];
        [_params enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSString *object, BOOL *stop) {
            [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"%@",object] dataUsingEncoding:NSUTF8StringEncoding]];
        }];

        [_imgParams enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSData *object, BOOL *stop) {
            if ([object isKindOfClass:[NSData class]]) {
                if (object.length > 0) {
                    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
                    DLog(@"Timestamp:%@",TimeStamp);
                    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.jpg\"\r\n",key,TimeStamp] dataUsingEncoding:NSUTF8StringEncoding]];
                    [body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
                    [body appendData:[NSData dataWithData:object]];
                }

            }
        }];

        [_videoParams enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSData *object, BOOL *stop) {
            if (object.length > 0) {
                [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
                DLog(@"Timestamp:%@",TimeStamp);
                [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.mp4\"\r\n",key,TimeStamp] dataUsingEncoding:NSUTF8StringEncoding]];
                [body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
                [body appendData:[NSData dataWithData:object]];
            }
        }];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [urlRequest setHTTPBody:body];
        AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = nil;
        manager.requestSerializer.timeoutInterval = 120.0f;


        NSURLSessionDataTask *dataTask = [manager uploadTaskWithStreamedRequest:urlRequest progress:^(NSProgress * _Nonnull uploadProgress) {

        } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            if(loading)
            {
                [ProgressHUD dismiss];
            }
            if (error) {

                [self showFailureMessage:error];

                DLog(@"Error: %@", error);
                if( _failure ){
                    _failure( error) ;
                }
            } else {
                DLog(@"response = %@", responseObject);
                if ([[responseObject valueForKey:RESPONSE_STATUS] intValue] == 1) {
                    if (_success) {
                        _success (responseObject);
                    }
                }else{
                    if( _failure ){
                        _failure( error) ;
                    }
                    showAlertWithErrorMessage([responseObject valueForKey:RESPONSE_MESSAGE]);
                }
            }
        }];
        [dataTask resume];
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM