Uploading an image using AFNetworking 3.0

后端 未结 3 843
礼貌的吻别
礼貌的吻别 2020-12-31 22:18

I tried to upload the image with using AFNetworking3.0. I have tried to find how to upload image from all stackoverflow and tutorial, but all of these are relative with AFNe

相关标签:
3条回答
  • 2020-12-31 22:54
    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.

    0 讨论(0)
  • 2020-12-31 23:14

    In AFNetworking 3.0 upload task works like this.

        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. I hope it will resolve your problem.

    0 讨论(0)
  • 2020-12-31 23:16

    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

        #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];
        }
    
    0 讨论(0)
提交回复
热议问题