I tried to download this geocode data - objective-c

Basically I am accessing this URL
http://maps.googleapis.com/maps/api/geocode/json?address=sudirman&sensor=true&bounds=-7.186696,105.7727|-5.186696,107.7727
However, the result is empty. Even though it should show something. I used objective-c
With this code:
response= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlresponse error:&error];
json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
I think the | need to be urlencoded. How to do so?

[NSURLConnection sendSynchronousRequest:request returningResponse:&urlresponse error:&error];
returns NSData, which when serialised will produce JSON, so you need to do:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error];
to get the JSON.

Related

Instagram API json data is truncated via app but ok in browser

Trying to parse simple JSON data from Instagram but stuck with this problem.
JSON data returns truncated in application, but everything is ok via browser on my mac.
Tried to do that many different ways, but all the same.
First way:
NSURL *instaGetRecentOwnerPhotosURL = [NSURL URLWithString:#"https://api.instagram.com/v1/users/self/media/recent/?access_token=MY_PROPER_TOKEN"];
NSData *jsonData = [NSData dataWithContentsOfURL:instaGetRecentOwnerPhotosURL];
Another way, assync:
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:#"https://api.instagram.com/v1/users/self/media/recent/?access_token=MY_PROPER_TOKEN"]];
__block NSDictionary *json;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(#"Async JSON: %#", json);
}];
JSON data returns like that:
screenshot of truncated json
Absolutely have no idea what is wrong.
It's not truncated. The log simply only shows part of the output. If it was really truncated it either wouldn't have parsed at all or it would just have fewer entries. But the data did parse. There is nothing wrong with json.
BTW - do proper error checking:
NSError *error = nil;
json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (json) {
// Data is good. Work with 'json'
} else {
NSLog(#"Unable to parse JSON. Error: %#", error);
}

Trying to parse JSON data from Flickr. Cocoa error 3840

I’ve never used an API in conjunction with web services before and I’m having trouble parsing the JSON data I’m receiving from Flickr’s API. The only thing I do know (from all the things I have read) is that it is easy and very simple. About as far as I can get is returning a string in the console. Using a dictionary returns null and or an error. What am I missing? I want to be able to pull out the id and owner so that I can get the photo url.
This returns data on my photo:
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#”%#”, json); //this returns data on my photo
This returns null(resultDict) and error 3840:
NSString *requestString = #”https://api.flickr.com/services/rest?&method=......etc;
NSURL *url = [NSURL URLWithString:requestString];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *task = [session dataTaskWithURL:url
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *resultdict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#”%#”, resultDict); //returns null
If (error != nil) { NSLog(#”%#”, [error localizedDescription]); }
else { self.myDict = [[resultDict objectforKey:#”photos”] objectAtIndex:0];
NSLog(#”%#”, self.myDict); }
}];
[task resume];
To check if I have an array of dictionaries I did the following and it returned 0:
NSMutableArray *resultArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainer error:&error]; error:&error];
NSLog(#"%lu", (unsigned long)resultArray.count);
Are you sure that
[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
returns a Dictionary and not an Array of Dictionnaries?
EDIT :
Can you try to use this to request the API please?
I checked in my projects, my reponses seems to have the same syntax as yours.
Only the code I use is different.
(If you could give us the full URL you've to call, it would be easier for us ^^')
NSString *str=#"YOUR URL";
NSURL *url=[NSURL URLWithString:str];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error: &error];
NSMutableDictionary* resultList = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
I copied it without the errors. I let you manage that ^^
NSMutableDictionary ***resultdict** = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#”%#”, **resultDict**); //returns null
resultdict and resultDict are not the same variables. I bet you have an instance variable or a global variable somewhere named resultDict. Instance variables should start with an underscore, among other reasons because it avoids problems like this.
For question maker this answer won't be actual but maybe for them who will face with such problem.
I had the same problem when tried to get data from flickr.photos.getRecent method. I forgot to add into URL parametrs value nojsoncallback=1.
Without it you get response in JSONP.

Assign single line json element to label in Objective-c

I'm trying to assign a simple json feed element to a label.
My json feed that looks like this:
[{"code":501,"data":{"req":"0"}}]
My code after I've retrieved it from a url:
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
NSArray* json_object = [NSJSONSerialization
JSONObjectWithData:POSTReply
options:0
error:nil];
NSArray *json_object_line = [json_object objectAtIndex:0];
mainLabel.Text= [json_object_line valueForKey:#"code"];
There is no way I can get this to work. The app simply crashes unless I remove the last 2 lines. I've tried a lot of other options (especially for the last 2 lines) to no avail.
Is there anything I'm doing wrong?
You tried to assign NSNumber to the label's text property. It's a reason of the crash. The proper way is to get a formatted string from JSON field:
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:POSTReply.bytes
length:POSTReply.length
encoding:NSASCIIStringEncoding];
NSArray* json_object = [NSJSONSerialization JSONObjectWithData:POSTReply
options:0
error:nil];
NSDictionary *json_object_line = json_object[0];
mainLabel.text= [NSString stringWithFormat:#"%#", json_object_line[#"code"]];

Send json string as httpBody data using objective c

I have been trying to send json string converted to nsdata to http body part.
but i always find that correct value is never passed on to
What i want on server :
{"request":"{\"Files\":[{'FileName':'11111111','FileType':'test'}]}"}
What i receive on server :
{"request":{"Files":[{"FileName":"test.html","FileType":"test"}]}}
Can anybody suggest me what am i doing wrong :
I tried following ways :
Way : 1
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:requestDict1 options:0 error:nil];
NSString* jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
Way : 2
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:requestDict1 options:0 error:nil];
[request setHTTPBody:jsonData];
Crust is i want to send nsdata format of json tring but i cant get perfect value on the server.
Can anybody suggest me a possible way to achieve this?
Try this one.
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:requestDict1 options:NSJSONWritingPrettyPrinted error:nil];
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[request setHTTPBody:jsonString];

TOUCHJSON Serialization from NSDictionary

I've read through the questions and answers related to TouchJSON serialization and I'm still not getting it to work.
I create an NSDictionary with sample data and used the JSONTouch serializer to convert the NSDictionary to JSON. However, when I log the NSData object 'theJSONData', it gives me this as a result:
<7b223131 31353535 34343434 223a2250
...
65227d>
Additionally, when I send this 'theJSONData' data to the web service (that's expecting JSON) this is what I get back:
2011-07-31 18:48:46.572 Street Lights[7169:207] Serialization Error: (null)
2011-07-31 18:48:46.804 Street Lights[7169:207] returnData: (null)
2011-07-31 18:48:46.805 Street Lights[7169:207] Error: Error Domain=kJSONScannerErrorDomain Code=-201 "Could not scan array. Array not started by a '[' character." UserInfo=0x4d51ab0 {snippet=!HERE>!?xml version="1.0" , location=0, NSLocalizedDescription=Could not scan array. Array not started by a '[' character., character=0, line=0}
What am I doing wrong? Does the JSON NSData object 'theJSONData' need to be converted to another type before I send it to the web service? Is there another step I'm missing?
// Create the dictionary
NSDictionary *outage = [[NSDictionary alloc] initWithObjectsAndKeys:
#"YCoord", #"12678967.543233",
#"XCoord", #"12678967.543233",
#"StreetLightID", #"666",
#"StreetLightCondition", #"Let's just say 'BAD'",
#"PhoneNumber", #"1115554444",
#"LastName", #"Smith",
#"Image",#"",
#"FirstName", #"Dawn",
#"Comments", #"Pole knocked down",
nil];
NSError *error = NULL;
// Serialize the data
NSData *theJSONData = [[CJSONSerializer serializer] serializeDictionary:outage error:&error];
NSLog(#"theJSONData: %#", theJSONData);
NSLog(#"Serialization Error: %#", error);
// Set up the request and send it
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://24.52.35.127:81/StreetLight/StreetlightService/CreateStreetLightOutage"]];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: theJSONData];
// Deserialize the response
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error:&error];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSData *theReturnData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
id theObject = [[CJSONDeserializer deserializer] deserializeAsArray:theReturnData error:&error];
NSLog(#"returnData: %#",theObject);
NSLog(#"Error: %#", error);
Thanks for everyone's help. I ended up using Fiddler to track what needed to be sent to the service in JSON and then saw I hadn't been formatting the header correctly. Here is the code that ended up working for me.
// Create the NSDictionary
NSDictionary *outage = [[NSDictionary alloc] initWithObjectsAndKeys:
#"12.543233",#"YCoord",
#"12.543233",#"XCoord",
#"111",#"StreetLightID",
#"Dented pole",#"StreetLightCondition",
#"1115554444",#"PhoneNumber",
#"Black",#"LastName",
[NSNull null],#"Image",
#"White",#"FirstName",
#"Hit by a car",#"Comments",
nil];
// Serialize the data
NSError *error = NULL;
NSData *theJSONData = [[CJSONSerializer serializer] serializeDictionary:outage error:&error];
NSLog(#"Serialization Error: %#", error);
// Change the data back to a string
NSString* theStringObject = [[NSString alloc] initWithData:theJSONData encoding:NSUTF8StringEncoding];
// Determine the length of the data
NSData *requestData = [NSData dataWithBytes: [theStringObject UTF8String] length: [theStringObject length]];
NSString* requestDataLengthString = [[NSString alloc] initWithFormat:#"%d", [requestData length]];
// Create request to send to web service
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://11.22.33.444:55/StreetLight/StreetlightService/CreateStreetLightOutage"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:requestDataLengthString forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval:30.0];
// Deserialize the response
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error:&error];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSData *theReturnData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
id theObject = [[CJSONDeserializer deserializer] deserializeAsArray:theReturnData error:&error];
NSLog(#"returnData: %#",returnString);
NSLog(#"Error: %#", error);
For one thing, you've got your objects and keys reversed in the NSDictionary.
I don't know enough about TouchJSON to help with that part of the code.
I am having similar issues in parsing a goodle v3 api response. Still no closer to resolving my issue, but one thing I have found that may be helpful to you is if you are using the deserializerAsArray then the JSON response must be enclose in "[" and "]" and if you are deserializerAsDictionary then the JSON response must be enclosed in "{" and "}".
As the google v3 api JSON response is in the "{" "}" format I need to use deserialiserAsDictionary method.
I suspect you know this already, but after looking at Jonathan Wight's code this is as far as I have come in resolving my own issue as Jonathan's code is specific in checking for the above in parsing the JSON response.
Thanks,
Tim