Search code examples
iosobjective-cxcodeafnetworkingafnetworking-2

How to convert NSURLConnection to AFNetworking?


i want to convert this code to AFNetworking but i have a error. i used

AFNetworking POST to REST webservice this code.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

NSString *latest_url = @"url_string";

[request setURL:[NSURL URLWithString:latest_url]];  

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:useragent_string forHTTPHeaderField:@"User-Agent"];
[request setValue:host_string forHTTPHeaderField:@"Host"];
[request setValue:@"keep-alive" forHTTPHeaderField:@"Connection"];
[request setValue:@"keep-alive" forHTTPHeaderField:@"Proxy-Connection"];
[request setTimeoutInterval:30.0];
[request setHTTPBody:postData];   

NSError *errorx = nil;

NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&errorx];

NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

NSData *jsonData = [json_string dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonerror;

NSData *get_data_from_request = [ourdelegate do_request:request_url post_array:request_post_array debug:istekdebug];

NSArray *statuses =[NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: &jsonerror];

How to convert this code to AFNetworking?


Solution

  • Since you are using post request, here's what you can do with AFHTTPSessionManager. You can also call AFHTTPSessionManager Get method with block invocation.

    NSURL *baseURL = [NSURL URLWithString:BaseURLString];
    NSDictionary *parameters = @{@"Host": host_string};
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    
    [manager POST:@"yourFile.php" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
             NSLog("handle succes");
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
             NSLog("handle error %@",[error localizedDescription]);
    }];
    

    Have fun :)