问题
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