How to create a nested json object - objective-c

"drive"=>{"admins_attributes"=>{"0"=>{"latitude"=>"42.2349343", "longitude"=>"-71.1133432"}, "1"=>{"latitude"=>"42.2349343", "longitude"=>"-71.1133432"}}}
Im trying to collect a bunch of latitudes and longitudes in objective c and save them to rails backend and using nested attributes but i can't figure out how to form this object like this in objective c. Each latitude and longitude has its own index.
NSDictionary *position = [[NSDictionary alloc] initWithObjectsAndKeys:
latitude, #"latitude",
longitude, #"longitude",
city, #"city",
state, #"state",
zipcode, #"zipcode",
carrName, #"carrier",
[NSNumber numberWithInt:signalStrength], #"signalStrength",
signalType, #"signalType",nil];
NSArray *positionArray = [NSArray arrayWithObjects:position, nil];
[positions addObject:positionArray];
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://localhost:3001/api/v1/drives"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:positions, #"positions_attributes", nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPBody:postData];
NSLog(#"JSON = %#", [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]);
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
}];
[postDataTask resume];

Related

How to fetch data using NSUrl session in objective-C?

I am trying to fetch JSON data and parse it using NSUrl session but getting null every time - Also in addition to that i want o show all data in table view
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"text/plain" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"text/plain" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"GET"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"Value", #"Key", nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Resopnse == %#",response);
if (response != nil) {
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"JSon dict === %#",jsonDict);
}
}];
[postDataTask resume];
May I know what i am doing wrong is anything other good way to do same?
Try following code.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"]];
[request setHTTPMethod:#"GET"];
[request addValue:#"text/plain" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"text/plain" forHTTPHeaderField:#"Accept"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSData * responseData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"requestReply: %#", jsonDict);
}] resume];
Please use the below code for the same. Hope it will solve your problem.
NSString *strUrl = [NSString stringWithFormat:yourUrl];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *dicResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(#"%#",dicResponse);
}
}];

How to check JSON post return value

I am new to JSON and I am trying to send a post I am wondering if how can I check if I did it properly or check the return value of it. Here's what I've done
NSURL *url = [NSURL URLWithString:#"http://json.myurl.com/.....];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"email", #"Email",
#"password", #"FirstName",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postdata];
For a beginner, I would recommend using third party framework, widely used by iOS developers across the world, called AFNetworking.
By using AFNetworking, HTTP requests are simple as that:
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
// TODO: Parse success here!
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// TODO: Parse failure here!
}];
In given example, object responseObject is a representation of API response JSON object.
Installation and further usage instructions of AFNetworking can be found in their website.
To check JSON POST return value:
NSString *strUrl=[NSString stringWithFormat:#"http://json.myurl.com/....."];
NSString *webStringURL = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:webStringURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"email", #"Email",
#"password", #"FirstName",
nil];
NSError* error;
NSData* postData = [NSJSONSerialization dataWithJSONObject:tmp options:NSJSONWritingPrettyPrinted error: &error];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *jsonData, NSError *error)
{
if (!error)
{
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(#"jsonResponse--->%#",jsonResponse);
});
}
else
{
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(#"error--->%#",error.description);
});
}
}];
And to check you JSON format is correct or not go through this link

How to post API through NSURLSession?

I have following code
How to parse response ?
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSURL *url = [NSURL URLWithString:# "API-URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"key", #"76658b01d08e43f65c6930933f69f1",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];
How to get dictionary output after getting response from dataTaskResponse?
Please Try the following Code.
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"json: %#", json);

Sending params with POST Req in JSON with AFNetworking

I have a small problem with AFNetworking.
I'm not able to send the parameters and the data to my server (php-Skript)
The data (from NSDictionary) have to be JSON.
Ignore the senseless code parts please.
I'm receiving Errors like:
NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
or Error: Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html"
NSDictionary *parameter = [[NSDictionary alloc]init];
parameter = #{#"device-id": #"iOSDeveloper1234567432",#"system": #1,#"token": #"iOS-TestToken",#"mail_enabled": #"false",#"mail": #"NULL", #"movies": #[#"matrix", #"matrix2", #"matrix3"]};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameter options:0 error:nil];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:URL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *stringkey;
stringkey = (#"k=");
stringkey = [stringkey stringByAppendingString:APIKEY];
NSString *strings;
NSString *myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
myString = [myString stringByAppendingString:(#"&k=")];
myString = [myString stringByAppendingString:APIKEY];
NSLog(#"%#",myString);
myString = [myString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = [myString dataUsingEncoding:NSSymbolStringEncoding];
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameter options:0 error:&error];
NSLog(#"%#",error.localizedDescription);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:URL parameters:myString progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

How to Retrive data from json post method through mvc controller web services using NSURLSESSION?

first of all please, click on this link then...
How I'm getting this output like name ,std & assign to textbox I'm already done this in xcode 5 but NSURLCOnnection not used in xcode 7.2 so Using NSURLSESSION How Can I bind to textbox??
NSError *error = nil;
NSMutableDictionary *dic2 = [[NSMutableDictionary alloc] init];
[dic2 setObject:#"324" forKey:#"grno"];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setObject:#"RestAPI" forKey:#"interface"];
[dic setObject:#"StudentLogin" forKey:#"method"];
[dic setObject:dic2 forKey:#"parameters"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://ios.skyzon.in/STudent/STudentDetail"]];
[req setHTTPMethod:#"POST"];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:postData];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:req
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
// NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
// NSLog(#"Data = %#",text);
NSMutableDictionary *responseDic = [[NSMutableDictionary alloc]init];
responseDic = [NSJSONSerialization JSONObjectWithData:postData options:NSJSONReadingAllowFragments error:&error];
NSLog(#"%#",responseDic);
self.txt.text = [responseDic objectForKey:#"Name"];
NSLog(#"%#",[responseDic objectForKey:#"Name"]);
}
}];
[dataTask resume];
You can you NSURLSESSION like below.
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:#"http://ios.skyzon.in/STudent/STudentDetail"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", json);
self.txt.text = [responseDic objectForKey:#"Name"];
}];
May be it will help you.