I am trying to fetch data from an url https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json
I am getting nil while converting nsdata to nsdictionary.
I used the following code. and I am able to log the data as well. but as soon as I convert it into dictionary it is showing nil.What am I missing here?
I tried nsurlsession and afnetworking as well. getting the same error.
NSError *error;
NSString *url_string = [NSString stringWithFormat: DATA_URL];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"json: %@", json);
Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.
In Swift, the NSDictionary class conforms to the DictionaryLiteralConvertible protocol, which allows it to be initialized with dictionary literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).
NSData provides methods for atomically saving their contents to a file, which guarantee that the data is either saved in its entirety, or it fails completely. An atomic write first writes the data to a temporary file and then, only if this write succeeds, moves the temporary file to its final location.
You have to convert NSData
into UTF8 before parsing it using NSJSONSerialization
.
NSError* error = nil;
NSString *strISOLatin = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
NSData *dataUTF8 = [strISOLatin dataUsingEncoding:NSUTF8StringEncoding];
id dict = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:0 error:&error];
if (dict != nil) {
NSLog(@"Dict: %@", dict);
} else {
NSLog(@"Error: %@", error);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With