json - Trying to get data from URL returns data is nil in objective c -
i currentley trying retrieve data link: http://steamcommunity.com/market/priceoverview/?country=us¤cy=3&appid=730&market_hash_name=%e2%98%85%20bayonet
i want data link outputs when go , click it.
here current code:
nsdata *data = [[nsdata alloc] initwithcontentsofurl:[nsurl urlwithstring:@"http://steamcommunity.com/market/priceoverview/?country=us¤cy=3&appid=730&market_hash_name=★%20bayonet"]]; nsdictionary *test = [nsjsonserialization jsonobjectwithdata:data options:kniloptions error:&error]; nslog(@"%@", test[@"lowest_price"]);
but currentley returns error:
*** terminating app due uncaught exception 'nsinvalidargumentexception', reason: 'data parameter nil'
i think has star involved in url string, have solution this?
your original url, in example code, malformed.
first, here's code works:
#import <foundation/foundation.h> int main(int argc, char *argv[]) { @autoreleasepool { nserror *error = nil; // note: pruned original '%20' in example -- partially escaped strings // difficult deal with. nsstring *urlstring = @"http://steamcommunity.com/market/priceoverview/?country=us¤cy=3&appid=730&market_hash_name=★ bayonet"; // now, escape entire string nsurl *url = [nsurl urlwithstring:[urlstring stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]]; // looks nslog(@"%@", [url absolutestring]); // http://steamcommunity.com/market/priceoverview/?country=us¤cy=3&appid=730&market_hash_name=%e2%98%85%20bayonet // run nsdata *data = [[nsdata alloc] initwithcontentsofurl:url]; nsdictionary *test = [nsjsonserialization jsonobjectwithdata:data options:kniloptions error:&error]; nslog(@"%@", test[@"lowest_price"]); //129,99€ // data weird me, looks appropriate. } }
first, didn't attempt escape string before using it. initwithstring:
docs state:
this method expects urlstring contain characters allowed in formed url. other characters must percent escaped. percent-escaped characters interpreted using utf-8 encoding.
so, that. however, original string in sample code "partially escaped". if escaped url, you'd end with:
http://steamcommunity.com/market/priceoverview/?country=us¤cy=3&appid=730&market_hash_name=%e2%98%85%2520bayonet
instead of
http://steamcommunity.com/market/priceoverview/?country=us¤cy=3&appid=730&market_hash_name=%e2%98%85%20bayonet
... can see, '%20' escaped '%2520'.
i hope helps. cheers.
Comments
Post a Comment