Calling web services with the help of AFNetworking in Objective C

前端 未结 1 860
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-22 06:23

I am using NSURLConnection method to call the web services what I want is to replace it with 3rd party library AFNetworking how shall I achieve this I am calling the web Ser

相关标签:
1条回答
  • 2020-12-22 07:23

    You need to send POST request to your web services. You can use below code snippet for old way.

    NSString *post = [NSString stringWithFormat:@"%@&value=%@&value=%@&value=%@&value=%@&value=%@",self.Comment_Memberid,self.SharedID,self.Post_Ownerid,self.commentText.text,email_stored,password_stored];
    
        NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://.../api/json/postcomment/"]]];
        [request setHTTPMethod:@"POST"];
        [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[postData length]] forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"text/plain; charset=utf-8" forHTTPHeaderField:@"Content-type"];
        //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-type"];
        [request setHTTPBody:postData];
        //get response
        NSHTTPURLResponse* urlResponse = nil;
        NSError *error = [[NSError alloc] init];
        NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
        NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"Response Code: %ld", (long)[urlResponse statusCode]);
    
        if ([urlResponse statusCode] == 200)
        {
    
        }
    

    And if you want to send POST request using with AFNetworking you can use below code:

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *params = @{@"34": x,
                             @"130": y};
    [manager POST:@"https://../api/json/cordinates" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    
    0 讨论(0)
提交回复
热议问题