Web Service App Crash That Doesn't Happen Too Frequently - ios

About a couple weeks ago, I submitted my JobSearch App to the App Store. This app uses the USA Job Search Web Service to get me the jobs in JSON data so that I can put those jobs into an array.
Anyway, my app got rejected due to a crash on the iPhone 5. I read the logs and they said
Exception Type: EXC_CRASH (SIGABRT)
So I created an exception breakpoint in my application. It turns out if I enter random garbage for my input, the web service might return me 0 jobs, and sometimes it will return SIGABRT. I found the crash at this line of my code, where I'm creating an array to hold the service:
NSMutableArray *jobsCallArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
I really can't find anything wrong with this code, and this is the only thing I need to fix to get my app accepted. If you would like to see how I call the service to it's entirety and all that, here is the code:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"push"])
{
NSString *urlString = [NSString stringWithFormat:#"http://api.usa.gov/jobs/search.json?query=%#+jobs+in+%#", [jobDescription text], [location text]];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableArray *jobsCallArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableArray *positionArray = [[NSMutableArray alloc] init];
for (NSDictionary *theJob in jobsCallArray)
{
NSString *jobDesc = theJob[#"position_title"];
[positionArray addObject:jobDesc];
}
FoundJobsTableViewController *detailVC = (FoundJobsTableViewController*)segue.destinationViewController;
[detailVC setArray:positionArray];
[detailVC setTheUrlString:urlString];
}
}
All help is appreciated, thanks in advance

You need to check for an error and whether you're actually receiving data:
if (!error && data) {
NSMutableArray *jobsCallArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}

Related

WatchConnectivity attempting to send data to Watch app

I'm trying to send data from my iOS app to the Watch app. I'm using the updateApplicationContext for this.
I have a json file that I converted in NSDictionary and tried to send it. But there is an error, here it is:
[WCSession updateApplicationContext:error:]_block_invoke failed due to WCErrorCodePayloadUnsupportedTypes
The file is correctly read.
Now here is the code that tries to send the data.
NSString *fileName = [[NSBundle mainBundle] pathForResource:#"data"
ofType:#"json"];
NSLog(fileName);
if (fileName) {
NSData *jsonData = [[NSData alloc] initWithContentsOfFile:fileName];
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:jsonData
options:0
error:&error];
if (error) {
NSLog(#"Something went wrong! %#", error.localizedDescription);
}
else {
NSLog(#"Rsens info: %#", data);
[WatchSessionManager.sharedManager updateApplicationContextWithApplicationContext:#{#"json": data} error:&error];
}
}
else {
NSLog(#"Couldn't find file!");
}
I read somewhere that the types that we could send were limited, but the dictionary was allowed. I'm sending a dictionary though.
Can you find what is the error?
[SOLUTION]
I found out that there were values of type long in my dictionary. In my JSON I had some properties that were transtyped in type long. Here is one of the properties before:
"state": 0
I just put my numbers in string quotes.
"state":"0"
Check the dictionary's content.
WatchConnectivity dictionaries can only contain property list types.

parse JSON weather object from Open Weather Map API using AFNetworking

I am using AFNetworking to retrieve information about the weather for a specific location, e.g:
http://api.openweathermap.org/data/2.5/weather?q={New%20York%20City}
I am using the AFNetworking framework but I am having the problems parsing some objects of the JSON.
If I have an NSDictionary with the MAIN object information from the JSON:
NSDictionay *main = [responseObject objectForKey:#"main"];
If I log the main NSDictionary I will get the following valid output:
"main":{
"temp":296.78;
"pressure":1011;
"humidity":69;
"temp_min":293.15;
"temp_max":299.82
};
Although if I create a NSDictionary containing the weather object I will get the following information whenever logging it to the console:
NSDictionay *weather = [responseObject objectForKey:#"weather"];
"weather":(
{
"id":801;
"main":"Clouds";
"description":"few clouds";
"icon":"02d"
}
);
The parsed information contains ( brackets instead of [ from the original response. This does not allow me to correctly access the inside attributes of the weather object.
Summing up, I am able to access all the inside variables of the MAIN object, but I cannot access the attributes of the Weather object (e.g access the icon attribute).
Can someone help me with this ?
Thank you,
You calling your service as below.
NSString *query = #"http://api.openweathermap.org/data/2.5/weather?q={New%20York%20City}";
NSLog(#"%#",query);
query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error] : nil;
Now print Response :
NSLog(#"weather==%#",[results objectForKey:#"weather"]);
NSLog(#"description==%#",[[[results objectForKey:#"weather"] objectAtIndex:0] objectForKey:#"description"]);
NSLog(#"icon==%#",[[[results objectForKey:#"weather"] objectAtIndex:0] objectForKey:#"icon"]);
NSLog(#"id==%#",[[[results objectForKey:#"weather"] objectAtIndex:0] objectForKey:#"id"]);
NSLog(#"main==%#",[[[results objectForKey:#"weather"] objectAtIndex:0] objectForKey:#"main"]);
Your Response is :
whwather==(
{
description = "sky is clear";
icon = 01d;
id= 800;
main= Clear;
}
)
description== "sky is clear";
icon == 01d;
id == 800;
main == Clear;

iOS - JSON Parsing error (blank logs)

Good day!
I'm having trouble parsing JSON in my ios app. I'm following this tutorial Click Here
This is my connectionDidFinishLoading code
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSArray *arrayOfArray = [allDataDictionary objectForKey:#"array"];
for (NSDictionary *diction in arrayOfArray) {
NSDictionary *zero = [diction objectForKey:#"0"];
NSString *foods = [zero objectForKey:#"foods"];
[array addObject:foods];
}
[[self myTableView]reloadData];
NSLog(#"%#",array);
}
The problem is, i don't have anything on my logs, its just
2015-01-14 11:19:51.992 NINETEEN[10299:246999] (
)
And also, this is my JSON File
[
{"id":"1",
"foods":"Baby Back Ribs",
"category":"Main",
"price":"P250",
"image_code":"0"},
{"id":"2",
"foods":"Bacon and Blue Cheese Burger",
"category":"Appetizer",
"price":"P300",
"image_code":"768"},
{"id":"3","foods":
"Frutti de Mare Pasta",
"category":"Pasta",
"price":"P180",
"image_code":"1536"}]
And this is it in JSON Viewer http://oi62.tinypic.com/zh36.jpg
Hope you can help me out, thanks!
The problem is this line:
NSArray *arrayOfArray = [allDataDictionary objectForKey:#"array"];
Your JSON document does not contain an element named array, so arrayOfArray is nil.

NSDictionary failed to read array in webservice

I'm newbie in developing Xcode 5 and unable to connect to SQLServer via php.
The php result is this:
{"user":[{"user_id":"2393", "id":"740049"}], "succeed":1}
This webservice created not by me but my team. I tried to track the process via NSLog and found the problem is NSDictionary i created unable to read this kind of format.
This is my NSDictionary
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:urlData option:NSJONReadingMutableContainers error:&error];
success=[json[#"success"] integerValue];
NSLog(#"Success:%ld", (long)success);
if my NSDictionary were able to read the data then the success should be 1 but it keep showing 0. I find the problem is that i cant parse that array in dictionary. Could anyone help me fix this thing?
You mistype the key value. it will be #"succeed". But you type #"success"
NSJSONSerialization *jsonData = [NSJSONSerialization JSONObjectWithData: urlData options:NSJSONReadingMutableContainers error:&error];
int success=[[(NSDictionary *)jsonData valueForKey:#"succeed"]integerValue];
NSLog(#"Success:%ld", (long)success);
Typo:
success=[json[#"succeed"] integerValue];
// ^^^^^^^
//returnString is {"user":[{"user_id":"2393", "id":"740049"}], "succeed":1};
NSDictionary *response = [returnString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *users =[NSArray alloc]init];
if([[response valueForKey:#"succeed"] integerValue] == 1)
users = [response valueForKey:#"user"];
for(NSDictionary *user in users)
NSLog(#"User : %#", user);
Sample Output
User: [{user_id:2393,id:740049},{user_id:2394,id:740050}...,{user_id:2395,id:740051}];

Count how many of a certain object appear in a JSON query

I'm returning JSON with a rough structure like the one below, and I'm trying to figure out how I can count how many platforms there are (in this case, three, but could be anything from 1 to 20 or so). I've returned the JSON into an NSDictionary and am using lines such as these to retrieve the data I need:
_firstLabel.text = _gameDetailDictionary[#"results"][#"name"];
In the above case, it'll grab the name from the results section. Since there are multiple platforms, I need to construct a loop to cycle through each name inside the platforms section. Not too sure how to go about that. All help appreciated!
"results":{
"platforms":[
{
"api_detail_url":"http://",
"site_detail_url":"http://",
"id":18,
"name":"First Name"
},
{
"api_detail_url":"http://",
"site_detail_url":"http://",
"id":116,
"name":"Second Name"
},
{
"api_detail_url":"http://",
"site_detail_url":"http://",
"id":22,
"name":"Third Name"
}
],
EDIT: Here's my fetchJSON method:
- (NSDictionary *) fetchJSONDetail: (NSString *) detailGBID {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: YES];
NSString *preparedDetailURLString = [NSString stringWithFormat:#"http://whatever/format=json", detailGBID];
NSLog(#"Doing a detailed search for game ID %#", detailGBID);
NSData *jsonData = [NSData dataWithContentsOfURL: [NSURL URLWithString:preparedDetailURLString]];
_resultsOfSearch = [[NSDictionary alloc] init];
if (jsonData) {
_resultsOfSearch = [NSJSONSerialization JSONObjectWithData: jsonData
options: NSJSONReadingMutableContainers
error: nil];
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: NO];
NSString *results = _resultsOfSearch[#"number_of_page_results"];
_numberOfSearchResults = [results intValue];
NSArray *platforms = [_resultsOfSearch valueForKey:#"platforms"];
int platformsCount = [platforms count];
NSLog(#"This game has %d platforms!", platformsCount);
return _resultsOfSearch;
}
The "platforms" JSON field is an array, so assuming you've de-serialised the JSON using something like,
NSMutableDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:resultsData options:NSJSONReadingMutableContainers error:&error];
Then, you can assign platforms to an NSArray,
NSDictionary *results = [responseJSON valueForKey:#"results"];
NSArray *platforms = [results valueForKey:#"platforms"];
...and find the number of platforms via,
int platformsCount = [platforms count];
In your case, where you want to iterate through the platforms, you can use,
for (NSDictionary *platform in platforms)
{
// do something for each platform
}

Resources