How to get json data in ios 6.1 xcode 4.6 - ios

How do I get data for the link: https://itunes.apple.com/us/rss/topalbums/limit=10/json using ios6.1 xcode 4.6.
Most of the codes are for ios5 and few use jsonKit. But does ios has any inbuilt json parsing now?
I am looking forward for using only for ios6.1 and not older versions.

NSError *requestError = NULL;
NSDictionary *myDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&requestError];
if (requestError){
//An error occurred.
}
The return type of +JSONObjectWithData is id. It could return an NSDictionary or an NSArray. Choose whichever fits your JSON data structure.
Where responseData is, well, the data from your response. If you have a string you want to parse, convert it to NSData: https://stackoverflow.com/a/6188605/985050

Related

JSON or NSDATA incomplete / truncated after server pull [duplicate]

This question already has answers here:
NSLog on devices in iOS 10 / Xcode 8 seems to truncate? Why?
(7 answers)
Closed 5 years ago.
I'm pulling a .json file from my server and trying to read it into an NSDictionary in my app. Some of the file is being correctly parsed but it is incomplete - only some of the file is being read.
The strange thing is that the NSData is an equal length to the actual file, so it seems that it has full access, at least at some stage. When I log the NSData however, it seems to be way too short for the size of the file.
Here's the code I'm using to find the bug:
//SYNC BOOL
if (isSyncing){ return; }
isSyncing = true;
//FETCH BOOTSTRAP
NSError * fetchError = nil;
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:syncPath]
options:kNilOptions
error:&fetchError];
if (fetchError){ [self error]; return; }
//PARSE JSON
NSError * jsonError = nil;
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&jsonError];
if (jsonError){ [self error]; return; }
NSLog(#"data length is %lu", data.length);
NSLog(#"json is %#", json);
I've tried loading remotely from the server and locally from NSBundle - same result.
Could this be related to encoding / a rogue character in the JSON / some NSData max length?
Those options on the NSData fetch method and JSON Serialisation method, I've always left blank with no issue in the past, in terms of what's being pulled it's the same. I've also tried requests and sessions etc with no love.
EDIT:
I should add that when I log the the .allKeys of the json dictionary, it returns all keys correctly (including those not included in the log of the dictionary itself). This coupled with the correct NSData length implies that the data is in fact there, in completion. An explanation would be if the NSLog itself is somehow being truncated, implying an error when none exists. The problem is I haven't changed anything there. It could be a beta bug in the new Xcode.
EDIT B:
Logger Error on Xcode 9?
NSString * string = #"";
for (int n = 0; n < 10000; n++){
string = [NSString stringWithFormat:#"%# %i",string,n];
}
NSLog(#"string is %#", string);
Outputs to 6.7k not 10k.
See if you get different results with:
NSLog(#"json is %#", json.description);
Or to rule out NSLog altogether, maybe breakpoint the code there, and right click on json in the variables pane of the debug area and choose Print description of "json"
My experience is NSJSONSerialization will return an error for malformed JSON.
This is some silly feature in Xcode itself it seems. This define works for the full NSLog:
#define NSLog(FORMAT, ...) printf("%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
Taken from here:
NSLog on devices in iOS 10 / Xcode 8 seems to truncate? Why?
How many developers will spend time looking for imaginary bugs in the lazy logger...
For those coming afterwards, I'm running Xcode 9.0.

The operation couldn’t be completed. (Cocoa error 3840.) for valid JSON

I'm trying to resolve the Cocoa error 3840 for a couple hours now. I've read all the answers posted here on stackoverflow and on any other sources I could find but nothing seems to help...
The problem is that I know this error occurs when there is something wrong with the JSON object you receive from the server but the JSON I'm receiving is valid. I've tested it on multiple JSON validators online and its checks out every time.
Here's my code:
NSError *localError = nil;
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&localError];
if (localError != nil) {
NSLog(#"%#", [localError localizedDescription]);
} else {
//NSDictionary *dict = [parsedObject objectForKey:#"status"];
//NSLog(#"%#", [dict objectForKey:#"message"]);
}
return parsedObject;
Heres a google drive link to the JSON: https://docs.google.com/document/d/1rC_--QiS85A82L2AohuqjC0JWIgVEAj68i7UUOxpvMw/edit?usp=sharing
This error only occurs for some responses that i get from the server. The same code works fine for other links from the same API.
I've tried this with NSArray instead of NSDictionary thinking that maybe the server might be serving an array instead of a hash, also tried changing the option value for JSONObjectWithData:data:options:error method but as you can guess nothing worked.
I'll greatly appreciate any help I can get.

How to filter json data using UISegmentedControl in iOS

I am working as iOS apps developer. The JSON response I need to consume is available at http://pastie.org/9304213 . Using this I want to filter the data so that in my UISegmentcontrol for 3 buttons. i.e 1. Day 2. Week 3.Month.
->If i click Date segment control it displays today data in UITableview controller.
->If i click Week segment control it displays current week data in UITableview controller.
->If i click Month segment control it displays current month data in UITableview controller.
I am new to iOS programming. Please guide.
This might help you. For fetching and parsing JSON data, You can use this in your Controller .m file. But do have a check on whether your server is sending you JSON in proper format or not. JSON should start with '[' or '{'.
NSURL *url=[NSURL URLWithString:#"yourServiceURL"];
NSData *response = [NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:response options: NSJSONReadingMutableContainers error: &error];
Now you have your data in a NSDictionary object and you can extract particular data using the objectForKey or valueForKey functions like this :
_array = [jsonArray valueForKey:#"keyField"];
Now if you want to toggle between 3 switch values, you can try something like this.
-(IBAction)segmentChanged:(id)sender
{
if ([_segmentControl selectedSegmentIndex]==0)
{
//your Code
}
else if ([_segmentControl selectedSegmentIndex]==1)
{
//your Code
}
else
{
//your Code
}
}
You have to connect this event with the valueChanged event of the UISegmentControl.This will do its job when you click on anyone of the segment values. It will identify the index of the clicked segment and will run into appropriate loop.
Hope this helps.

Using GCKMediaControlChannel's sendTextMessage method yields error

With google cast iOS SDK, The GCKMediaControlChannel's sendTextMessage method is straightforward and it's hard to mis-use so I am guessing this may be a bug in the SDK ... hopefully someone will prove me wrong so I can get back to work!
Here's the code:
NSDictionary *messageDict = #{
#"message": #"blah",
#"num":[NSNumber numberWithInt:2]
};
NSError *error;
NSData *msgData = [NSJSONSerialization dataWithJSONObject:messageDict
options:0
error:&error];
NSString *message = #"" ;
if (!msgData) {
DDLogError(#"ERROR serializing message: %#", error);
return NO ;
} else {
message = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];
[self sendTextMessage:message] ;
}
...the receiver produces this error when the message is received [cast.receiver.mediaManager] Ignoring request, requestId is not an integer: undefined
At first view it seems like GCKMediaControlChannel inherits directly its sendTextMessage method from the GCKCastChannel, failing to implement some of the messaging aspects specific to the media channel (in particular failing to wrap the message in a media-style envelope with the requestId and mediaSessionID attributes)
Has anybody else encountered this? Am I missing something? Is there a workaround?
I followed the recommendation on the ticket I created, messaging to the receiver media app using a custom namespace using GCKCastChannel instead of he dedicated GCKMediaControlChannel to work around the issue. The ticket response confirms "don't use sendTextMessage directly with the GCKMediaControlChannel"

iOS 5 Json and utf8 problems

I use the iOS 5 JSON features to load data from web.
My target is to get some twitter data - the data is filtered via web and I get it via the following url:
http://botpwn.org/ios/getfollowers.json?uid=63964843
Thats working and I dont have problems there - but my problems begin with parsing the data in my app.
I load the data here
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://botpwn.org/ios/getfollowers.json?uid=%#", my_uid]]];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
-(void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
latestFollower = [json objectForKey:#"followers"]; //2
for (int i = 0; i < [latestFollower count]; i++){
[temp addObject:[latestFollower objectAtIndex:i]];
}
if (latestFollower == nil || latestFollower.count == 0){
NSLog(#"No followers");
}
}
And now I always get the answer that I have an empty latestFollower array - and I know that the problem is, that some names (not screennames) of twitter users contain special chars and iOS can't parse it.
I searched for solutions (set the php header to utf8 etc.) but nothing helps.
Maybe you have an idea how to parse it right, or maybe I'm doing something wrong but i don't get it.
EDIT: Just fixed it myself - finally I used a tool (http://jsonlint.com/) to check whether there is an error in the json output and yes - it was. Thanks for your ideas ! :)
Just fixed it myself - finally I used a tool (http://jsonlint.com/) to check whether there is an error in the json output and yes - it was. Thanks for your ideas ! :)

Resources