How to insert the data into sqlite - objective-c

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]

Related

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];
}

Manipulating Facebook/JSON data

I'm trying to handle Facebook JSON data and transform it into a NSMutable Dictionary, but I'm getting (null) when I try to print the data. Although when I try to do a count, I get a number.
User_likes is NSMutableDictionary which is globally defined. I'm getting (null) on this line:
NSLog(#"User likes: %#", user_likes);
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 {
user_likes = [NSJSONSerialization JSONObjectWithData:results options:kNilOptions error:&error];
NSLog(#"User likes: %#", user_likes);
NSInteger* n_user_likes = [results count];
NSInteger* n_user_likes2 = [user_likes count];
NSLog(#"n user likes %qi", n_user_likes);
NSLog(#"n user likes2 %qi", n_user_likes2);
id val = nil;
id values = [[user_likes allKeys] objectAtIndex:0 ];
NSLog(#"values id %#", values);
When I print results, I get a lot of data from Facebook, this is a sample of it:
data = (
{
"page_id" = 253370381511811;
type = "PUBLIC FIGURE";
},
{
"page_id" = 148389618201;
type = "LOCAL BUSINESS";
},
{
"page_id" = 213631462169238;
type = COMMUNITY;
},
{
"page_id" = 162297750451425;
type = "NON-PROFIT ORGANIZATION";
},
{
"page_id" = 503620106320217;
type = "MEDIA/NEWS/PUBLISHING";
},
you can't do directly
user_likes = [NSJSONSerialization JSONObjectWithData:results options:kNilOptions error:&error];
you need first create a dictionary with the data in results like this:
NSDictionary *dictionary = [NSDictionary dictionaryWithJSONData:results];
user_likes = [NSString stringWithFormat:#"%d",[[dictionary objectForKey:#"value_of_the_likes"] intValue]];
NSLog(#"%#",user_likes);
NSLog(#"%#",dictionary);
EDIT:
Please, create this class to your project and import in the class where you need use this.
#import <Foundation/Foundation.h>
#interface NSDictionary (JSONExtensions)
+(NSDictionary*)dictionaryWithJSONData:(NSData*)data;
-(NSData*)JSONValue;
-(NSString*)JSONString;
#end
#implementation NSDictionary(JSONExtensions)
+(NSDictionary*)dictionaryWithJSONData:(NSData*)data{
NSError *error = nil;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error){
NSLog(#"%#",error);
return nil;
};
return result;
}
-(NSData*)JSONValue{
NSError *error = nil;
NSData *result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];
if(error){
NSLog(#"%#",error);
return nil;
};
return result;
}
-(NSString*)JSONString{
return [[NSString alloc] initWithData:self.JSONValue encoding:NSUTF8StringEncoding];
}
#end
Hope it can help you.
maybe you forget set up options:
NSJSONReadingOptions options = NSJSONReadingAllowFragments | NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves;
user_likes = [NSJSONSerialization JSONObjectWithData:results options:options error:&error];
i hope this be useful for you!
UPDATE:
Check this :
NSJsonSerialzation not parsing results from Facebook - Cocoa error 3840
Let me know if that helps you!

NSCFString objectAtIndex: unrecognized selector sent to instance Objective C [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am trying to get some json data and show it as text in a UILabel but I keep on getting a app crash with the following error -[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x1f8cfff0?
Here is my code and the json response. I see in my log that I am getting the Name from the call but the app bombs out the that error. I have 2 UILabel blocks, one of which shows a text format of the json response and the other the actual json response in text.
I'm trying to pull the name of the person, I can see Bilbo Baggins in the log when the json comes back.
Here is my json output:
{"ProfileID":34,"ProfilePictureID":20,"Name":"Bilbo Baggins","Clients":[{"ClientID":91,"Name":"Fnurky"},{"ClientID":92,"Name":"A different client"},{"ClientID":95,"Name":"Second Community"},{"ClientID":96,"Name":"Britehouse"}]}
and my code to try show it as a uilabel as text.
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString: #"http://www.ddproam.co.za/Central/Profile/JSONGetProfileForUser"] //2
#import "JsonViewController.h"
#interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress;
-(NSData*)toJSON;
#end
#implementation NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress
{
NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: urlAddress] ];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
-(NSData*)toJSON
{
NSError* error = nil;
id result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
#end
#implementation JsonViewController
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* defineJsonData = [json objectForKey:#"Name"]; //2
NSLog(#"Name: %#", defineJsonData); //3
// 1) Get the latest loan
NSDictionary* loan = [defineJsonData objectAtIndex:0];
// 3) Set the label appropriately
humanReadble.text = [NSString stringWithFormat:#"Hello: %#",
[(NSDictionary*)[loan objectForKey:#"Name"] objectForKey:#"Name"]];
//build an info object and convert to json
NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:
[loan objectForKey:#"Name"],
nil];
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:info
options:NSJSONWritingPrettyPrinted
error:&error];
//print out the data contents
jsonSummary.text = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
}
#end
A combination of – sorry – poor var names and lost in a complex structure.
First:
Here you get the complete JSON as Dictionary:
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
According to your Q, this has this structure:
{
"ProfileID":34,
"ProfilePictureID":20,
"Name":"Bilbo Baggins",
"Clients":
[
{
"ClientID":91,
"Name":"Fnurky"
},
{
"ClientID":92,
"Name":"A different client"
},
{
"ClientID":95,
"Name":"Second Community"
},
{
"ClientID":96,
"Name":"Britehouse"
}
]
}
Second:
With the next statement, you simply get the name of obviously something like a person:
NSArray* defineJsonData = [json objectForKey:#"Name"]; //2
There is the root:
what you get – look at your JSON – is:
"Name":"Bilbo Baggins",
You get the object for the key Name. The var, holding the reference to the result should be called expressing this. Let's change this:
NSArray* name = [json objectForKey:#"Name"]; //2
Next – look at your JSON – the object behind that key is an instance of NSString, not NSArray. Let's repair this:
NSString* name = [json objectForKey:#"Name"]; //2
Third:
Doing so will the compiler make throwing out an error. This is because of this statement:
NSDictionary* loan = [defineJsonData objectAtIndex:0];
Changed to the new var name:
NSDictionary* loan = [name objectAtIndex:0];
The compiler is right: You do not have an array, so you cannot send objectAtIndex:.

Native Facebook/iOS6 integration: Cocoa error 3840 when trying to get profile picture

I am currently using only Social.framework (no FacebookSDK) and getting starting with requesting and getting access to basic user data. Here's all the code I have (with a few properties declared outside, as you'll notice). Everything works fine in terms of getting the right permissions, but I'm getting the following output error when asking for user's profile picture:
2013-01-27 21:28:44.324 TestApp[9230:1a703] Account saved to accountStore
2013-01-27 21:28:45.002 TestApp[9230:1d603] (null)
2013-01-27 21:28:45.003 TestApp[9230:1d603] Request error: The operation couldn’t be completed. (Cocoa error 3840.)
And here is the code:
- (IBAction)btnFbLoginPressed:(id)sender
{
ACAccountType *fbAccountType = [self.accountStore accountTypeWithAccountTypeIdentifier: ACAccountTypeIdentifierFacebook];
NSArray *permissions = #[#"email"];
self.requestAccessOptions = #{ACFacebookAppIdKey:FB_API_KEY, ACFacebookPermissionsKey:permissions, ACFacebookAudienceKey:ACFacebookAudienceOnlyMe};
[self.accountStore requestAccessToAccountsWithType:fbAccountType options:self.requestAccessOptions completion:^(BOOL granted, NSError *e) {
if (granted && e == nil) {
NSArray *readPermissions = #[#"user_photos"];
NSDictionary *readAcccessOptions = #{ACFacebookAppIdKey:FB_API_KEY, ACFacebookPermissionsKey:readPermissions, ACFacebookAudienceKey:ACFacebookAudienceOnlyMe};
[self.accountStore requestAccessToAccountsWithType:fbAccountType options:readAcccessOptions completion:^(BOOL granted, NSError *e) {
if (granted && e == nil) {
NSArray *accounts = [self.accountStore accountsWithAccountType:fbAccountType];
self.facebookAccount = [accounts lastObject];
[self.accountStore saveAccount:self.facebookAccount withCompletionHandler:^(BOOL success, NSError *error) {
if (error != nil || !success) {
NSLog(#"Error saving account to accountStore: %#", error.localizedDescription);
} else {
NSLog(#"Account saved to accountStore");
}
}];
NSString *uid = [NSString stringWithFormat:#"%#", [[self.facebookAccount valueForKey:#"properties"] valueForKey:#"uid"]];
NSString *url = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture", uid];
NSURL *profilePictureURL = [NSURL URLWithString:url];
SLRequest *profilePictureRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodGET URL:profilePictureURL parameters:nil];
profilePictureRequest.account = self.facebookAccount;
[profilePictureRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *e)
{
NSDictionary *responseDataDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&e];
NSLog(#"%#", responseDataDictionary);
if (e != nil) {
NSLog(#"Request error: %#", e.localizedDescription);
} else {
}
}];
} else {
NSLog(#"Read permissions request error: %#", e.localizedDescription);
}
}];
} else {
NSLog(#"Basic permissions request error: %#", e.localizedDescription);
}
}];
}
You can see that the reponseDataDictionary is null and something happens when parsing the data. I noticed a couple of other threads on SO about the same error code, but no luck so far. My guess is that either 1) there's something wrong with my Facebook code, or 2) I'm parsing the data incorrectly. Any help's appreciated!
Note: I would like to stick to using the Social/Account frameworks only.
UPDATE: Slight modification thanks to a suggestion in the comments.
Changed code:
[profilePictureRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *e)
{
NSLog(#"Request error value: %#", e.localizedDescription);
NSError *jsonError = nil;
NSDictionary *responseDataDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&jsonError];
NSLog(#"Response data dictionary value: %#", responseDataDictionary);
if (jsonError != nil) {
NSLog(#"Serialization error: %#", jsonError.localizedDescription);
} else {
NSLog(#"Serialization successful");
}
}];
Output:
2013-01-28 18:55:16.265 TestApp[9565:1ae03] Account saved to accountStore
2013-01-28 18:55:17.640 TestApp[9565:1b503] Request error value: (null)
2013-01-28 18:55:17.640 TestApp[9565:1b503] Response data dictionary value: (null)
2013-01-28 18:55:17.642 TestApp[9565:1b503] Serialization error: The operation couldn’t be completed. (Cocoa error 3840.)
The profilePictureRequest is returning an image and not JSON. Use + (CIImage *)imageWithData:(NSData *)data to convert the response to an image.

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);
}