Volunteermatch API Objective C

How to make json post request?

Try this

    NSDictionary *objectDic = @{@"username" : username, @"password" : password};
NSDictionary *dataDic = @{@"data" : objectDic};
NSDictionary *methodDic = @{@"method" : @"login", @"data": dataDic};

NSData *requestData = [NSJSONSerialization dataWithJSONObject:methodDic
options:NSJSONWritingPrettyPrinted
error:nil];
[request setHTTPBody: requestData];

objective c parse json from url request

Do this way:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.

[responseData appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSError *e = nil;
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e];

}

AFNetworking 2.0 Send Post Request with array of dictionary Parameters

just add

Step-1

// create the dictionary of {"name":"abc","phone":"1234567890"},{"name":"Kate Bell","phone":"9925992599"} this

NSDictionary *params = @{@"name": @"hello",
@"phone": @"1234567890"};

Step-2

//create the one array of this output [ {"name":"abc","phone":"1234567890"},{"name":"Kate Bell","phone":"9925992599"} ]

NSMutableArray *arr = [NSMutableArray arrayWithObjects:params,nil];

Step-3

// convert your object to JSOn String
NSError *error = nil;
NSString *createJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:objectsInCart
options:NSJSONWritingPrettyPrinted
error:&error]
encoding:NSUTF8StringEncoding];

Step-4

//create the another one dictionary for send the data for like data=[ {"name":"abc","phone":"1234567890"},{"name":"Kate Bell","phone":"9925992599"} ]

NSDictionary *pardsams = @{@"data": createJSON};

Step-5

  // finally start your request
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

NSLog(@"Dict %@",pardsams);
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];

[manager POST:@"http://forapp.com/api/getContacts.php" parameters:pardsams success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);

}];

How can I migrate in AFNetworking 3.0?

NSURL *url = [NSURL URLWithString:@"https://example.com/"];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:

height, @"user[height]",

weight, @"user[weight]",

nil];

[httpClient postPath:@"/myobject" parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {

NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

NSLog(@"Request Successful, response '%@'", responseStr);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
}];

iOS 9 Best solution for parsing JSON

The problem is that the completion handler does not run on the main queue. But all UI updates must happen on the main queue. So dispatch that to the main queue:

[[session dataTaskWithURL:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// handle response
NSError *parseError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
// do something with `json`
dispatch_async(dispatch_get_main_queue()), ^{[collectionView reloadData]});
}] resume];

afnetworking 3.0 Migration: how to POST with headers and HTTP Body

I was able to figure this out myself.

Here's the solution.

First, you need to create the NSMutableURLRequest from AFJSONRequestSerializer first where you can set the method type to POST.

On this request, you get to setHTTPBody after you have set your HTTPHeaderFields. Make sure to set the body after you have set the Header fields for content-type, or else the api will give a 400 error.

Then on the manager create a dataTaskWithRequest using the above NSMutableURLRequest. Don't forget to resume the dataTask at the very end or else nothing will get sent yet. Here's my solution code, hopefully someone gets to use this successfully:

NSDictionary *body = @{@"snippet": @{@"topLevelComment":@{@"snippet":@{@"textOriginal":self.commentToPost.text}},@"videoId":self.videoIdPostingOn}};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]] parameters:nil error:nil];

req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];


[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {

if (!error) {
NSLog(@"Reply JSON: %@", responseObject);

if ([responseObject isKindOfClass:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(@"Error: %@, %@, %@", error, response, responseObject);
}
}] resume];

AFNetworking - do not cache response

Make long story short, just define your AFNetworking manager:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];

Enjoy!



Related Topics



Leave a reply



Submit