简体   繁体   中英

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?

Since you aren't being specific with the error like rckoenes mentioned above.......

Why don't you just go get PAW from LuckyMarmot

It helps you formulate REST api calls and will translate the request into AFNetworking for you. Phenomenal tool for only $19.99. Worth every penny.

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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