Solicitud de publicación de AFNetworking


82

Soy un novato en obj-c y he estado usando asihttp para algunos de mis proyectos. Al hacer una solicitud de publicación en asihttp, se hace de esta manera.

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setPostValue:height forKey:@"user[height]"];
    [request setPostValue:weight forKey:@"user[weight]"];
    [request setDelegate:self];
    [request startAsynchronous];

¿Cómo haría AFNetworking con un ejemplo de código?
Ya obtuve el getrequest get Json funcionando en AFNetworking, pero esta solicitud de publicación me está dando algunos problemas. Gracias por la ayuda de antemano.

Respuestas:


212

Primero vale la pena agregar (ya que esta respuesta sigue siendo popular 6 años después de que la escribí inicialmente ...) que lo primero que debe considerar es si debe usar AFNetworking. NSURLSession se agregó en iOS 7 y significa que no necesita usar AFNetworking en muchos casos, y una biblioteca de terceros menos siempre es algo bueno.

Para AFNetworking 3.0:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"user[height]": height,
                         @"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

Para AFNetworking 2.0 (y también usando la nueva sintaxis NSDictionary):

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = @{@"user[height]": height,
                         @"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

Si está atascado con AFNetworking 1.0, debe hacerlo de esta manera:

NSURL *url = [NSURL URLWithString:@"https://example.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        height, @"user[height]",
                        weight, @"user[weight]",
                        nil];
[httpClient postPath:@"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"Request Successful, response '%@'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
}];

Muchas gracias Joseph, funcionó muy bien. Acabo de tener una pregunta después de asignar el httpClient. Lo libero después de crear la solicitud, no parece que haya fallas y parece funcionar bien. Solo quería confirmar que ese es el lugar correcto para lanzarlo. Muchas gracias de nuevo. Saludos cordiales
Sam Barnet

2
Sí, eso funcionaría. El AFHTTPClient está realmente diseñado para mantenerse y usarse nuevamente si realiza otra solicitud, pero liberarlo inmediatamente después de la llamada 'requestWithMethod:' es aceptable.
JosephH

Hola Joseph, finalmente lo hice funcionar con una respuesta json y configuré otra pregunta stackoverflow.com/questions/7630289/… para saber realmente si lo estoy haciendo bien. Muchas gracias, siento molestarme.
Sam Barnet

2
A estas alturas, parece que ya no hay más método "operationWithRequest: completado" para AFHTTPRequestOperation ... simplemente use "initWithRequest" y luego "setCompletionBlockWithSuccess".
e-cal

@Rakesh Es difícil responder correctamente una pregunta como esa en los comentarios. ¿Puedo sugerirle que abra una nueva pregunta, por favor?
JosephH

32
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                       height, @"user[height]",
                       weight, @"user[weight]",
                       nil];

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:
                                             [NSURL URLWithString:@"http://localhost:8080/"]];

[client postPath:@"/mypage.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
     NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
     NSLog(@"Response: %@", text);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"%@", [error localizedDescription]);
}];

12

Aquí hay un POST de AFNetworking simple que estoy usando. Para ponerme en marcha después de leer el documento de AFNetworking, wkiki, ref, etc., aprendí mucho siguiendo http://nsscreencast.com/episodios/6-afnetworking y entendiendo el ejemplo de código asociado en github.

 // Add this to the class you're working with - (id)init {}
    _netInst = [MyApiClient sharedAFNetworkInstance];

  // build the dictionary that AFNetworkng converts to a json object on the next line
  //  params = {"user":{"email":emailAddress,"password":password}};
  NSDictionary *parameters =[NSDictionary dictionaryWithObjectsAndKeys:
                             userName, @"email", password, @"password", nil];
  NSDictionary *params =[NSDictionary dictionaryWithObjectsAndKeys:
                         parameters, @"user", nil];

   [_netInst postPath: @"users/login.json" parameters:params
      success:^(AFHTTPRequestOperation *operation, id jsonResponse) {
        NSLog (@"SUCCESS");

        // jsonResponse = {"user":{"accessId":1234,"securityKey":"abc123"}};
        _accessId = [jsonResponse valueForKeyPath:@"user.accessid"];
        _securityKey = [jsonResponse valueForKeyPath:@"user.securitykey"];

        return SUCCESS;
      }
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"FAILED");

        // handle failure

        return error;
      }
   ];  

¿El responseObject se analiza automáticamente en JSON?
zakdances

2
    AFHTTPClient * Client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://urlname"]];
    NSDictionary * parameters = [[NSMutableDictionary alloc] init];
    parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                 height, @"user[height]",
                        weight, @"user[weight]",
                  nil]; 

    [Client setParameterEncoding:AFJSONParameterEncoding];
    [Client postPath:@"users/login.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);

    NSLog(@"response string: %@ ", operation.responseString);

    NSDictionary *jsonResponseDict = [operation.responseString JSONValue];
        if ([[jsonResponseDict objectForKey:@"responseBody"] isKindOfClass:[NSMutableDictionary class]]) {
            NSMutableDictionary *responseBody =  [jsonResponseDict objectForKey:@"responseBody"];
           //get the response here


    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"error: %@", operation.responseString);
        NSLog(@"%d",operation.response.statusCode);

    }];

Espero que esto funcione.


2

Para AFNetworking 4

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"user[height]": height,
                         @"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params headers:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

1

Aquí un ejemplo con Swift 3.0

let manager = AFHTTPSessionManager(sessionConfiguration: URLSessionConfiguration.default)
manager.requestSerializer = AFJSONRequestSerializer()
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")

if authenticated {
    if let user = UserDAO.currentUser() {
        manager.requestSerializer.setValue("Authorization", forHTTPHeaderField: user.headerForAuthentication())
    }
}

manager.post(url, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, responseObject: Any?) in 
    if var jsonResponse = responseObject as? [String: AnyObject] {
        // here read response
    }
}) { (task: URLSessionDataTask?, error: Error) in
    print("POST fails with error \(error)")
}

1
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
[SVProgressHUD show];

NSDictionary *dictParam =@{@"user_id":@"31"};// Add perameter

NSString *URLString =@"your url string";

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];//strGlobalLoginToken is your login token
//         [manager.requestSerializer setValue:setHeaderEnv forHTTPHeaderField:@"Env"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:URLString parameters:dictParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {

     NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];

     NSLog(@"Response DICT:%@",response);

     if ([[[[response objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
     {

         for (NSMutableDictionary *dicAll in [[[response objectForKey:@"response"]objectAtIndex:0]objectForKey:@"plans"])
         {
             [yourNsmutableArray addObject:[dicAll mutableCopy]];
         }
         //yourNsmutableArray Nsmutablearray  alloction in view didload

         NSLog(@"yourNsmutableArray  %@",yourNsmutableArray);
     }
     else
     {
         NSLog(@"False");
     }

     [SVProgressHUD dismiss];

 } failure:^(NSURLSessionDataTask  *_Nullable task, NSError  *_Nonnull error)
 {
     NSLog(@"RESPONSE STRING:%@",task.response);
     NSLog(@"error userInfo:%@",error.userInfo);

     NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
     NSLog(@"URLString :--->>   %@ Error********* %@",URLString,errResponse);

     [SVProgressHUD dismiss];

 }];

0

Para AFNetworking 3.0 y Swift. Tal vez podamos usar así:

let configutation = NSURLSessionConfiguration.defaultSessionConfiguration()
manager = AFHTTPSessionManager(sessionConfiguration: configutation)

let urlString = "url"
manager.POST(urlString, parameters: [params here], progress: nil, success: { (dataTask: NSURLSessionDataTask, response: AnyObject?) -> Void in
        print(dataTask)
        print(response)
        }) { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
        print(error)
}

¡Espero que esto ayude a otros a encontrar una respuesta como yo!


0

Para AFNetworking 3.0 ( iOS9 o greter )

 NSString *strURL = @"https://exampleWeb.com/webserviceOBJ";
    NSDictionary *dictParamiters = @{@"user[height]": height,@"user[weight]": weight};

    NSString *aStrParams = [self getFormDataStringWithDictParams:dictParamiters];

    NSData *aData = [aStrParams dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *aRequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strURL]];
    [aRequest setHTTPMethod:@"POST"];
    [aRequest setHTTPBody:aData];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
    [aRequest setHTTPBody:aData];

    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:aRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        //
        if (error ==nil) {
            NSString *aStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"ResponseString:%@",aStr);
            NSMutableDictionary *aMutDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                    completionBlock(aMutDict);

                NSLog(@"responce:%@",aMutDict)

            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"error:%@",error.locali)
            });
        }
    }];

    [postDataTask resume];

y añadir

-(NSString *)getFormDataStringWithDictParams:(NSDictionary *)aDict
{
    NSMutableString *aMutStr = [[NSMutableString alloc]initWithString:@""];
    for (NSString *aKey in aDict.allKeys) {
        [aMutStr appendFormat:@"%@=%@&",aKey,aDict[aKey]];
    }
    NSString *aStrParam;
    if (aMutStr.length>2) {
        aStrParam = [aMutStr substringWithRange:NSMakeRange(0, aMutStr.length-1)];

    }
    else
        aStrParam = @"";

    return aStrParam;
}

Ese código no usa AFNetworking en absoluto. Es solo un ejemplo de cómo usar NSURLSession.
JosephH

0
NSURL *URL = [NSURL URLWithString:@"url"];


AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"prefix":@"param",@"prefix":@"param",@"prefix":@"param"};
[manager POST:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    self.arrayFromPost = [responseObject objectForKey:@"data"];
    // values in foreach loop


    NSLog(@"POst send: %@",_arrayFromPost);
} failure:^(NSURLSessionTask *operation, NSError *error) {


    NSLog(@"Error: %@", error);
}];

0
NSMutableDictionary *dictParam = [NSMutableDictionary dictionary];
[dictParam setValue:@"VALUE_NAME" forKey:@"KEY_NAME"]; //set parameters like id, name, date, product_name etc

if ([[AppDelegate instance] checkInternetConnection]) {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictParam options:NSJSONWritingPrettyPrinted error:&error];                                             

    if (jsonData) {
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"Api Url"]
                                                               cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                           timeoutInterval:30.0f];
        [request setHTTPMethod:@"POST"];

        [request setHTTPBody:jsonData];
        [request setValue:ACCESS_TOKEN forHTTPHeaderField:@"TOKEN"];

        AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        op.responseSerializer = [AFJSONResponseSerializer serializer];
        op.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];

        [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
         arrayList = [responseObject valueForKey:@"data"];
         [_tblView reloadData];
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         //show failure alert
         }];
        [op start];
    }
} else {
    [UIAlertView infoAlertWithMessage:NO_INTERNET_AVAIL andTitle:APP_NAME];
}

0
please try below answer.

+(void)callAFWSPost:(NSDictionary *)dict withURL:(NSString *)strUrl 
withBlock:(dictionary)block
{
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
[manager POST:[NSString stringWithFormat:@"%@/%@",WebserviceUrl,strUrl] parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {
     if (!responseObject)
     {
         NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
         [dict setObject:ServerResponceError forKey:@"error"];
         block(responseObject);
         return ;
     }
     else if ([responseObject isKindOfClass:[NSDictionary class]]) {
         block(responseObject);
         return ;
     }
 }
      failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
 {
     NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
     [dict setObject:ServerResponceError forKey:@"error"];
     block(dict);
 }];
}

0

para la pantalla de inicio de sesión;

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary 

dictionaryWithObjectsAndKeys:_usernametf.text, @"username",_passwordtf.text, @"password", nil];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];

[manager POST:@"enter your url" parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"%@", responseObject);

}
      failure:^(NSURLSessionTask *operation, NSError *error) {
          NSLog(@"Error: %@", error);
      }];

}


0
// For Image with parameter /// AFMultipartFormData

NSDictionary *dictParam =@{@"user_id":strGlobalUserId,@"name":[dictParameter objectForKey:@"Name"],@"contact":[dictParameter objectForKey:@"Contact Number"]};

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:webServiceUrl]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:@"update_profile" parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    if (Imagedata.length>0) {
        [formData appendPartWithFileData:Imagedata name:@"profile_pic" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
    }
} progress:nil
      success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {
     NSLog(@"update_profile %@", responseObject);

     if ([[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
     {
         [self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
             [self.navigationController popViewControllerAnimated:YES];

         }] animated:YES completion:nil];


     }
     else
     {
         [self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
         }] animated:YES completion:nil];

     }
     [SVProgressHUD dismiss];

 } failure:^(NSURLSessionDataTask  *_Nullable task, NSError  *_Nonnull error)
 {
     [SVProgressHUD dismiss];
 }];

-1

Con AFNetworking 3.0, debe escribir:

NSString *strURL = @"https://exampleWeb.com/webserviceOBJ";
NSURL * urlStr = [NSURL URLWithString:strURL];

NSDictionary *dictParameters = @{@"user[height]": height,@"user[weight]": weight};

AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];


[manager POST:url.absoluteString parameters:dictParameters success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"PLIST: %@", responseObject);
   
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
    
}];

Esto se ve bien, pero creo que OP estaba buscando cómo enviar una solicitud POST.
patrick.ryan93
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.