Null form JSON file when using dataWithContentsOfURL - ios

I'm trying to connect to a JSON file on my server (witch is a valid JSON file), but it returns NULL(jsonData is NULL not the json). The code works whit other url's but not with mine, and when loaded in a web browser every thing is fine.
Here is the code i'm using.
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];

Use the following method to get the possible error in loading the data with your url:
NSError *error = nil;
NSData *jsonData = [NSData dataWithContentsOfURL:url
options:NSDataReadingUncached
error:&error];
if (error) {
NSLog(#"error: %#", error);
} else {
// ... do stuff
}
A common error to occur in a development environment is when the server you are calling is on a local network and you are trying to access from a device on an external network. Make sure this is not the case.

I think the problem is you are passing url as string. Passed it as a url. Use this for converting into data:-
NSData *jsonData =[NSData dataWithContentsOfURL:[NSURL URLWithString:yoururlString]];

Related

No visible #interface for 'NSMutableArray' declares the selector 'getObjectAtIndex:'

I am making this app that gets some data from the url (censored). The problem is that I didn't found a solution to get what the PHP script echo.
A normal returned array from that script looks this:
{"user_data": {"id":"78","image":"https://www.i********p.com/uploads/ideas/fun/2017/03/28/78.jpg","idea":"Join Facebook groups related to your passions or hobbies and meet friends.","owner_ID":"1","owner":"Eduard","owner_photo":"https://www.i********p.com/uploads/members/1/1.png","rating":"4","reviews":"1 review","msg":"success"}}
The question is how can I access each value of this array from "user_data" using Objective-c (without a loop)?
The Objective-c code:
- (void)getJSON {
NSError *error;
NSString *url_string = [NSString stringWithFormat: #"https://www.app.i******o.com/getidea.php?topic=%#", ideasTopic];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error) {
NSLog(#"Something went wrong: %#", error);
} else {
NSLog(#"json: %#", json);
NSLog(#"IMAGE: %#", [[json getObjectAtIndex:0] getObjectForKey:#"image"]);
}}
Objective-C supports literal version to access dictionary. You can directly access values by using keys.
NSString *imageUrl = json[#"user_data"][#"image"];
Your json is a dictionary of dictionaries. json[#"user_data"] returns a dictionary with keys and values. You can access values for this dictionary through respective keys. json[#"user_data"][#"image"] gives you required value for respective key.
Edit:
You need to change your json variable type to NSDictionary too.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
The JSON text you provided is deserialized into NSDictionary object (you can check it yourself, by looking up what class a json variable has in your example).
So to get what you want (ex. image), you simply write
json["user_data"]["image"]

How can I modify to fix this code?

I'm a new in iOS.
I always use from JSON string to extract value data which I want. But, I faced that make a JSON string and send to web server.
I have to make a JSON string this -> "errorCode":"1491"
and my code is below.
NSString *jsonRt = #"{ \"errorCode\":\"1491\"}";
NSLog(#"[D] jsonRt : %#", jsonRt);
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[jsonRt dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:NULL];
NSLog(#"jsonObject=%#", jsonObject);
NSError *error;
NSData *jsdata = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:&error];
NSLog(#"jsdata=%#", jsdata);
return [NSString stringWithFormat:#"%#",jsdata];
If build and run this code, my app is stop. I can't debug from breakpoint because suddenly jammed step over button. Where I fix this code?
I forgot the function return type. This is NSString*.

How to parse {status:0,val:450} from a HTML response

i want to take 450
from the following:
NSString {status:0,val:450}
using objective c:
{status:0,val:450}
Please suggest me answer
I cannot completely understand your question . I think you have you have an JSON data like:
{
status:0;
val:450;
}
If you want this data in your app. You want to do
NSURL *blogURL = [NSURL URLWithString:#"https://your url here"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *data = [dataDictionary objectForKey:#"status"];
NSDictionary *item = [data objectForKey:#"val"];
Your JSON Data get in Dictionary format. You can access the Data using the Key. In here your keys are status and val.
I hope this links are help for you.
fetch parse json ios programming tutorial
and this Link:
json parsing in ios

Can reusing the same NSError object be problematic?

I have since changed my implementation to not do this anymore, but I would be interested in knowing if the following could lead to issues - take for example a process that has multiple steps, each involving passing a reference to an NSError object. If you were to reuse this error object each step along the way, would that reference be negatively effected in some way, perhaps leading to some sort of memory management/dealloc crash?
Example (most of the in-between code has been omitted)
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:&error];
if (!data) {
return error;
}
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (!responseData) {
return error;
}
NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
if (!resultDictionary) {
return error;
}
Even though the error is never "used" twice, meaning the error will be nil (it seems) the next time its reference is passed to another method, could the reference be effected in some way at any of the steps along the way?
Original code prior to editing in response to jlehr's comments:
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:&error];
if (error) {
return;
}
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) {
return;
}
NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
if (error) {
return;
}
EDIT: To anyone coming to this at a later date, the information jlehr is referring to can be found here:
When dealing with errors passed by reference, it’s important to test
the return value of the method to see whether an error occurred, as
shown above. Don’t just test to see whether the error pointer was set
to point to an error.
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/ErrorHandling/ErrorHandling.html
According to Apple's documentation, you should never check an NSError object returned by reference. Instead, check the return value of the init... method or factory method you're calling, for example:
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:&error];
if (data == nil) {
// Handle failure. It's safe to use the error object here.
}
However, your code doesn't appear to be doing anything with the NSError instance, (e.g., logging, or displaying an alert), so you can just pass NULL instead.
NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:NULL];
if (data == nil) {
// Handle failure.
}

XML to JSON conversion in ios

i'm trying to convert a simple xml document in Xcode to JSON. The problem is keep returning nil.
This is my code:
NSURL *url = [[NSURL alloc] initFileURLWithPath:#"http://www.w3schools.com/xml/note.xml"];
NSData *xmlData = [[NSData alloc] initWithContentsOfURL:url];
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLData:xmlData error:&parseError];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:xmlDictionary
options:NSJSONWritingPrettyPrinted
error:&error];
NSLog(#"%#", jsonData);
Error message:
[NSJSONSerialization dataWithJSONObject:options:error:]: value parameter is nil'
As rmaddy said, try printing parseError. If parseError is Nil, then try printing the xmlDictionary, and check if the dictionary is created correctly.
If xmlDictionary is also Nil, then check the xmlData, which should be fine, in which case the dictionaryForXMLData method must be verified if it checks for any conditions.
Hope I helped.

Resources