Post method using Afnetworking in Objective-C

南楼画角 提交于 2019-12-25 09:25:01

问题


How to write the code to sending POST method for the below JSON format using Afnetworking.

{
Media
  {
      Photo : image.jpg, 
      UserId : 2
  },
Personal
  {
      Name : aaa, 
      Age   : 30
  }, 
Education
  {
    College : xxx, 
    Course : yyy    

  }, 
} 

回答1:


Obviously that's not quite the actual format, but we can guess what you might have meant. Clearly, if those numeric values (the user id and age) are expected as strings, then quote then, but hopefully it illustrates what the Objective-C representation of that dictionary might look like:

NSDictionary *parameters = @{@"Media": @{@"Photo": @"image.jpg", @"UserId": @2}, @"Personal": @{@"Name": @"aaa", @"Age": @30}, @"Education": @{@"College": @"xxx", @"Course": @"yyy" }};

Then you can post it as JSON like so:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

[manager POST:@"https://yoururl.com" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSLog(@"responseObject = %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"error %@", error);
}];

And if your server doesn't support HTTPS, but only HTTP, then you might have to alter your Info.plist's "App Transport Security Settings" to "Allow Arbitrary Loads".




回答2:


Firstly make a dictionary of params you want to send

NSDictionary *params = @{
                                     @"contact_no":@"9898989898",
                                     @"password":@"••••••••••"
                                     };

Then write the following code

AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
    operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
    operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
operationManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
        [operationManager POST:urlString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
            NSLog(@"%@",responseObject);

        } failure:^(AFHTTPRequestOperation *operation, NSError *error){
            if (failure)
                NSLog(@"%@",error.localizedDescription);
        }];

You can neglect the line in which i am setting the acceptableContentTypes.

Hope this will help.



来源:https://stackoverflow.com/questions/41604093/post-method-using-afnetworking-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!