WatchConnectivity attempting to send data to Watch app - ios

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.

Related

How to parse JSON data from textual file in Objective-C

I know, JSON parsing questions are asked over and over again, but still I can't find any answer to this one.
I've been trying to read and parse a textual JSON file using NSJSONSerialization to no avail.
I've tried using the same JSON data from a NSString and it did work.
Here's the code:
NSError *error;
NSString *jsonString1 = [NSString stringWithContentsOfFile:jsonFilePath
encoding:NSUTF8StringEncoding
error:&error];
NSData *jsonData1 = [jsonString1 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject1 = [NSJSONSerialization JSONObjectWithData:jsonData1
options:0
error:&error];
NSString *jsonString2 = #"{\"key\":\"value\"}";
NSData *jsonData2 = [jsonString2 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject2 = [NSJSONSerialization JSONObjectWithData:jsonData2
options:0
error:&error];
- The text file contains one line: {"key":"value"}
- jsonString1 = #"{"key":"value"}"
- jsonString2 = #"{\"key\":\"value\"}"
- jsonData1 is 23 bytes in size
- jsonData2 is 15 bytes in size
- jsonObject1 is nil and I get error code 3840
- jsonObject2 is a valid dictionary
Seems like the problem is with reading the file, since the NSStrings and NSDatas differ, but what am I doing wrong here and how can I fix it?
Most likely you file contains some unprintable characters (e.g. \0) that trigger the failure. Printing the error message will tell you at what position the first invalid characters occurs.
For example, try printing "{\"key\":\u{0000}\"value\"}" and you'll seem to get a valid JSON, however decoding it fails.
I always do a check on the return value when doing anything with NSUTF8StringEncoding and if nil, then try NSASCIIStringEncoding:
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (jsonString == nil) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
}
return jsonString;

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;

Parsing JSON object for iOS application

Currently, I have within my iPhone app a URL with which contains a JSON object that I must parse.
I am able to fetch the JSON object, convert the object to an NSString, now the issue is parsing the object/NSString object.
I am currently using SBJSON.
How do I go about iterating through the key elements of the JSON object using SBJSON's framework?
{
"status":"SUCCESS",
"fields":[
{
"type":"instant",
"field":"GenerationPower",
"label":"now",
The JSON object is MUCH larger than just these keys and key elements but once this issue is resolved, I'm sure the rest of the JSON object will be easy since i'll have a reference.
Thank you Stackoverflow!
EDIT:
Here's some code to clarify my issue.
+ (NSString *) pullingInfo
{
NSURL *solarWebURL = [NSURL URLWithString:myurl];
if (solarWebURL)
{
NSLog(#"Calling: %#", solarWebURL);
NSData *jsonData = [NSData dataWithContentsOfURL:solarWebURL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}
NSString* errorMessage = #"Error reading URL";
return errorMessage;
}
+ (NSDictionary *) jsonDictionaryObject
{
NSDictionary * jsonDictionary = [[NSDictionary alloc] init];
NSString * monroeString = [MonroeParser pullingInfo];
return jsonDictionary;
}
So as I said before, I have already loaded the JSON object into an NSString object "jsonString". Now I would like to start parsing the string.
I figure I may not even need to use JSON's framework for parsing, I can probably just parse the NSString using NSString conventions provided by Apple.
Any idea's? But maybe this isn't efficient....
Sine you are using SBJSON, why are you even converting the NSData to an NSString? You can use -objectWithData method for SBJSONParser to directly read the NSData into an NSDictionary.
http://sbjson.org/api/3.2/Classes/SBJsonParser.html#//api/name/objectWithData:
Let pullingInfo return an id. And in you calling function check if the id is of type NSDictionary or NSArray and parse accordingly.

Write JSON from textfields to a file for iOS 5+

I'm new to iOS programming, and having trouble finding a beginner-level explanation of how to write the contents of multiple text fields to a local json file in such a way to keep everything organized.
For example, a user form would have Name, Address, Email, etc., which would need to be put into a Customer object.
The purpose of this is to save data from several forms, and eventually pass that data to a database.
You'll need to convert your text fields into a dictionary (or dictionary of dictionaries). Once you have that done, you convert the dictionary into JSON data and save that:
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myJSONDict options:0 error:&error];
if (jsonData != nil) {
NSString *jsonFilePath = ...;
BOOL status = [jsonData writeToFile:jsonFilePath atomically:YES];
if (!status) {
NSLog(#"Oh no!");
}
} else {
NSLog(#"My JSON wasn't valid: %#", error);
}
You just need to create the path and check the status.
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
[dict setObject:form.name.text forKey:#"name"]'
[dict setObject:form.address.text forKey:#"address"];
...
NSString* jsonString = [yourFavoriteJsonTool convertToJson:dict];

iOS 5 JSON Parsing Results in Cocoa Error 3840

I'm having a hard time parsing the below JSON string on iOS 5.
{"States": [{"Name": "Arizona","Cities": [{"Name": "Phoenix"}]},{"Name": "California","Cities": [{"Name": "Orange County"},{"Name": "Riverside"},{"Name": "San Diego"},{"Name": "San Francisco"}]},{"Name": "Nevada","Cities": [{"Name": "Las Vegas"}]}]}
And here's my code:
- (void) parseJson {
NSError *jsonError = nil;
NSData *jsonData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Locations-JSON" ofType:#"rtf"]];
if (jsonData) {
NSDictionary *jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&jsonError];
if (jsonError) {
NSLog(#"JSON Error: %#", [jsonError localizedDescription]);
return;
}
NSLog(#"%#", jsonObjects);
}
}
I keep getting this error:
JSON Error: The operation couldn’t be completed. (Cocoa error 3840.)
I'd appreciate some help on this because I clearly and incapable of fixing this.
One thing that strikes me as incorrect is this:
[[NSBundle mainBundle] pathForResource:#"Locations-JSON" ofType:#"rtf"]
Your data is an RTF file?? It should be a txt file (or any other sort of plain text file). RTF files usually contain text formatting data, like this:
{\rtf1\ansi\ansicpg1252\cocoartf1138\cocoasubrtf470
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural
\f0\fs24 \cf0 \{"States": [\{"Name": "Arizona","Cities": [\{"Name": "Phoenix"\}]\},\{"Name": "California","Cities": [\{"Name": "Orange County"\},\{"Name": "Riverside"\},\{"Name": "San Diego"\},\{"Name": "San Francisco"\}]\},\{"Name": "Nevada","Cities": [\{"Name": "Las Vegas"\}]\}]\}}
When I read that in as a data and try to parse it as JSON, I get the 3840 error you're seeing. That error's description says:
The data couldn’t be read because it has been corrupted. (No string key for value in object around character 2.)
So what it looks like to me is that you don't actually have JSON. You have RTF data.
I had hit a similar problem. My JSON parser works intermittently when I download the JSON data from a server. Did you get your JSON data from this function?
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
The NSData returned from this function could be partial data. You need to appendData to an instance variable with type: NSMutableData. Then you process your JSON in another function as follows:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
Reading this article for the details. It works for me
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
I was able to troubleshoot my JSON 3840 error by converting the NSData object to an NSString:
NSError *error;
NSObject *object = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if (object == nil) {
NSString *serverResponse = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"\n\nError:\n%#\n\nServer Response:\n%#\n\nCrash:", error.description, serverResponse);
[NSException raise:#"Invalid Data" format:#"Unable to process web server response."];
}
If you arrived here because of the JSON and not because of the RTF , please check out this answer :
IOS JSON Deserialization failure - STIG/NSJSONSerializer

Resources