Facebook json data error, cocoa error 3840 - objective-c

I'm trying to get data from Facebook, but I'm getting this error when I try to parse the data to a Dictionary:
Mistake: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (No value.) UserInfo=0x144ad420
This is my code:
NSString *query =
#"SELECT page_id, type FROM page_fan WHERE uid = me() ";
// Set up the query parameter
NSDictionary *queryParam = #{ #"q": query };
// Make the API request that uses FQL
[FBRequestConnection startWithGraphPath:#"/fql"
parameters:queryParam
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection,
id results,
NSError *error) {
if (error) {
NSLog(#"Error: %#", [error localizedDescription]);
} else {
BOOL can = [NSJSONSerialization isValidJSONObject:results];
NSLog(#"can %d", can);
NSError *mistake;
NSDictionary *first = [NSJSONSerialization JSONObjectWithData:results options:0 error:&mistake];
if (mistake) {
NSLog(#"Mistake: %#", mistake);
} else {
NSLog(#"No mistake");
}
the can identifier returns '1' so I'm assuming the error is not with the data that Facebook is providing.
The data from Facebook is returning fine, this is a sample of results:
data = (
{
"page_id" = 253370381511811;
type = "PUBLIC FIGURE";
},
{
"page_id" = 148389618201;
type = "LOCAL BUSINESS";
},
{
"page_id" = 213631462169238;
type = COMMUNITY;
}

I don't know that library, but the code that you wrote cannot possibly work.
isValidJSONObject is a method that checks whether you have an object that can be serialised to JSON, that is an NSArray or NSDictionary containing only keys and values that can be serialised to JSON.
JSONObjectWithData is a method that takes an NSData object and deserialises it to an NSArray or NSDictionary.
Since an NSData object will always fail in isValidJSONObject, and an NSDictionary or NSArray is never valid input for JSONObjectWithData, one of these calls must fail.

Related

Parse json from URL in objective c

I am trying to parse some JSON from a URL in objective C.
The output is fine, however, when I try to get the value of the notifications.id key it returns a SIGBRT error.
Code:
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&serializeError];
success = [jsonData[#"ERROR"] integerValue];
if (success == 0) {
NSLog(#"%#", jsonData[#"notifications"][#"id"]);
}else{
}
Example JSON is:
{"notifications":[{"id":"fae9a890-2791-46e2-ad9c-5a72f602a2e8","created":"2017-06-17T21:57:28+00:00","thread_id":3964,"reply_id":null,"thread":{"id":3964,"subject":"[CakePHP]
Pagination"},"users_from":{"username":"Royal"},"content":"has posted a
reply
in"},{"id":"00732627-f23e-423e-b885-add968575972","created":"2017-06-17T20:08:05+00:00","thread_id":3964,"reply_id":79478,"thread":{"id":3964,"subject":"[CakePHP]
Pagination"},"users_from":{"username":"Royal"},"content":"has quoted
you in"}]}
How can I fix this?
Thanks.
The object for key notifications is clearly an array. Please read the JSON: [] is array, {} is dictionary.
NSArray *notifications = jsonData[#"notifications"];
for (NSDictionary * notification in notifications) {
NSLog(#"%#", notification[#"id"]);
}

How to implement ChimpKit3?

I'm having big difficulties following the example in the ChimpKit readme on github.
NSDictionary *params = #{#"id": #"8ce4588803", #"email": #{#"email": #"foo#example.com"}, #"merge_vars": #{#"FNAME": #"Freddie", #"LName":#"von Chimpenheimer"}};
[[ChimpKit sharedKit] callApiMethod:#"lists/subscribe" withParams:params andCompletionHandler:^(ChimpKitRequest *request, NSError *error) {
NSLog(#"HTTP Status Code: %d", request.response.statusCode);
NSLog(#"Response String: %#", request.responseString);
if (error) {
//Handle connection error
NSLog(#"Error, %#", error);
dispatch_async(dispatch_get_main_queue(), ^{
//Update UI here
});
} else {
NSError *parseError = nil;
id response = [NSJSONSerialization JSONObjectWithData:request.responseData
options:0
error:&parseError];
if ([response isKindOfClass:[NSDictionary class]]) {
id email = [response objectForKey:#"email"];
if ([email isKindOfClass:[NSString class]]) {
//Successfully subscribed email address
dispatch_async(dispatch_get_main_queue(), ^{
//Update UI here
});
}
}
}
}];
Apparently this is the code to subscribe an email to a list in MailChimp
I am getting errors:
/SubscribeEmailViewController.m:146:105: Expected ')'
SubscribeEmailViewController.m:146:103: Type specifier missing,
defaults to 'int'
SubscribebeEmailViewController.m:147:44: Use of undeclared identifier
'request'
SubscribeEmailViewController.m:146:103: Incompatible block pointer
types sending 'int ((^)(void))' to parameter of type
'ChimpKitRequestCompletionBlock' (aka 'void (^)(NSURLResponse
*__strong, NSData *__strong, NSError *__strong)')
This is basically copy and paste from the example, I can't figure out what detail I'm missing here.
ChimpKit was installed via cocoapods

Sending Xcode data to JSON

I am fairly new to xcode but I currently have an app that will send data to a sql database but I know it has to go through JSON first.
Say my app is simply a text box where a user enters a name and submits. How would I turn that data into JSON? What would the syntax look like?
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/
If you are sending the data through a network, then look into AFNetworking.
(added in response to a comment)
NSString *jsonFromObject(id object)
{
NSError* error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject: object options: 0 error: &error];
if (error) {
NSLog(#"error creating json string: %#", error);
}
return [[NSString alloc] initWithData: jsonData encoding: NSASCIIStringEncoding];
}

How to insert the data into sqlite

I am working on iPhone application and getting response from server and i parse the response string using JSON Parser it returns the dictionary. now i am not under stand how to use the data because it is came with back slash, i have print the data on console i am sending this related image please check the image give a solution to me. i am working on this problem from the last 6hrs onwards. please give me solution.!
(
"{\"category_id\":\"1\", \"category_name\":\"BEVERAGES\", \"image_id\":\"6\"}",
"{\"category_id\":\"1\", \"category_name\":\"BEVERAGES\", \"image_id\":\"7\"}",
"{\"category_id\":\"3\", \"category_name\":\"BREAKFAST\", \"image_id\":\"5\"}",
"{\"category_id\":\"3\", \"category_name\":\"BREAKFAST\", \"image_id\":\"6\"}",
"{\"category_id\":\"4\", \"category_name\":\"ALA CARTE\", \"image_id\":\"2\"}
),
(
"{\"subcategory_id\":\"1\",\"category_id\":\"3\", \"subcategory_name\":\"COMBOS\", \"image_id\":\"\"}",
"{\"subcategory_id\":\"2\",\"category_id\":\"3\", \"subcategory_name\":\"OMELETES\", \"image_id\":\"\"}",
"{\"subcategory_id\":\"3\",\"category_id\":\"3\", \"subcategory_name\":\"GRIDDLES\", \"image_id\":\"\"}"
),
NSError* error = nil;
NSArray* jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if (jsonArray == nil) {
NSLog(#"Error getting jsonArray: %#", error);
// Handle error condition
}
NSArray* categoryArray = jsonArray[0];
for (NSString* innerJson in categoryArray) {
NSData* innerJsonData = [innerJson dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* innerDict = [[NSJSONSerialization JSONObjectWithData:innerJsonData options:0 error:&error];
if (innerDict == nil) {
NSLog(#"Error getting innerDict: %#", error);
// Handle error condition
}
NSString* category_id = innerDict[#"category_id"];
// etc
}
// Repeat for subcategoryArray = jsonArray[1]

Parsing JSON: Checking for object existence and reading values

My application returns a NSMutableData *receivedData.
I've opted for using NSJSONSerialization to parse this under the assumption that it would be easiest. I'm having extreme trouble trying to get my head around how to do it. I'm very new to Objective-C, from a Java background.
In Java I used gson to parse the JSON in to an array which I could use easily. I'm really struggling with this here.
My current code for parsing the JSON is:
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: receivedData options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", item);
}
}
As provided by somebody on the internet. This works and prints two items to NSLog. result and header. Here is how the JSON looks:
{
"header":{
"session":"sessionid",
"serviceVersion":"1",
"prefetchEnabled":true
},
"result":"50ce82401e826"
}
However if there is an error the JSON can also look like this:
{
"header":{
"session":"sessionid",
"serviceVersion":"1",
"prefetchEnabled":true
},
"fault":{
"code":0,
"message":"someErrorCode"
}
}
How I want the code to work:
Check if there is a "fault" object
If there is, print fault.code and fault.message to NSLog
If there isn't, I know that my JSON contains result instead of fault
Print the value of result to NSLog
But I can't for the life of me figure out how to approach it. Can someone please give me some pointers?
your object appears to be a dictionary.
Try this out.
NSError *e = nil;
id jsonObj = [NSJSONSerialization JSONObjectWithData: receivedData options: NSJSONReadingMutableContainers error: &e];
NSArray *jsonArray = nil;
NSDictionary *jsonDict = nil;
if ([jsonObj isKindOfClass:[NSArray class]]){
jsonArray = (NSArray*)jsonObj;
}
else if ([jsonObj isKindOfClass:[NSDictionary class]]){
jsonDict = (NSDictionary*)jsonObj;
}
if (jsonArray != nil) {
// you have an array;
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", item);
}
}
else if (jsonDict != nil){
for (NSString *key in jsonDict.allKeys){
NSLog(#"Key: %# forItem: %#",key,[jsonDict valueForKey:key]);
}
}
else {
NSLog(#"Error: %#",e);
}