R-JSON

APPDELEGATEG.H

//
// AppDelegate.h
// JSONParser
//
// Created by Nikunj Ladani on 22/03/13.
// Copyright (c) 2013 Nikunj Ladani. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) UINavigationController *navigationController;
@end

 

APPDELEGATE.M

//
//  AppDelegate.m
//  JSONParser
//
//  Created by Nikunj Ladani on 22/03/13.
//  Copyright (c) 2013 Nikunj Ladani. All rights reserved.
//

#import “AppDelegate.h”

#import “ViewController.h”

@implementation AppDelegate

– (void)dealloc
{
[_window release];
[_navigationController release];
[super dealloc];
}

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {

//Call database here

[self createEditableCopyOfDatabaseIfNeeded];

ViewController *masterViewController = [[[ViewController alloc] initWithNibName:@”ViewController” bundle:nil] autorelease];
self.navigationController = [[[UINavigationController alloc] initWithRootViewController:masterViewController] autorelease];
self.window.rootViewController = self.navigationController;
}
[self.window makeKeyAndVisible];
return YES;
}

//Database methods

– (void)createEditableCopyOfDatabaseIfNeeded {

//NSLog(@”Creating Editable copy of Wondersofworld”);
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@”database”];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@”database”];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];

}

– (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

– (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

– (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

– (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

– (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

WebAPIRequest.h

#import <Foundation/Foundation.h>

 

@interface WebAPIRequest : NSObject {
}

 
+(void)sample:(NSObject *)delegate username:(NSString*)strUserName password:(NSString*)password Tag:(int)tagID;
@end

WebAPIRequest.m

//
//  WebAPIRequest.m
//
//  iWeather
//
//  Created by Anand Nair on 6/8/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.

#import “WebAPIRequest.h”

@interface NSObject(Extended)

//for regular json parser
-(void)setTradeData:(NSString *)message items:(NSString *)items withtag:(int)tag;

@end

@interface ConnectionClass:NSObject{
NSMutableData *receivedData;
NSString *className;
NSString *rootName;
NSObject *m_delegate;
int tag;
}
-(id)initWithClass:(NSString *)class withRoot:(NSString *)root withDelegate:(NSObject *)delegate withTag:(int)t;
@end

@implementation ConnectionClass
-(id)initWithClass:(NSString *)class withRoot:(NSString *)root withDelegate:(NSObject *)delegate withTag:(int)t
{
m_delegate = delegate;
className = class;
rootName = root;
tag=t;
return self;
}
– (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
if (receivedData != nil) {
[receivedData appendData:data];
} else {
receivedData = [[NSMutableData alloc] initWithData:data];
}
}

– (void)connectionDidFinishLoading:(NSURLConnection *)connection {

if([className length]==0) {
NSMutableArray *item=[[NSMutableArray alloc] initWithObjects:rootName,receivedData,nil];
//[m_delegate setData:@”” items:item withtag:tag];
[item release];
}
else {

//Parse Json data
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *strData = [[NSString alloc]  initWithBytes:[receivedData bytes]
length:[receivedData length] encoding: NSUTF8StringEncoding];

[m_delegate setTradeData:@”” items:strData withtag:tag];
[strData release];
[pool release];
}
}

-(void)dealloc {
[receivedData release];
[super dealloc];
}
– (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[m_delegate setTradeData:@”” items:nil withtag:0];

}

@end

@implementation WebAPIRequest
//Regular method for json parser
+(void)sample:(NSObject *)delegate username:(NSString*)strUserName password:(NSString*)password Tag:(int)tagID{//Registration

int tag = 1;

// NSString *urlString = [NSString stringWithFormat:@”http://122.182.14.104:3004/build/product/15.json?username=’%@&passowrd=’%@'&#8221;,strUserName,password];

NSString *urlString = [NSString stringWithFormat:@”https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=flower&as_filetype=png&imgsz=medium”%5D;

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@”GET”];

ConnectionClass *con = [[[ConnectionClass alloc]initWithClass:@”login” withRoot:@”” withDelegate:delegate withTag:tag]autorelease];

[[[NSURLConnection alloc]initWithRequest:request delegate:con] autorelease];

}

@end
ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
NSString *strUserName;
NSString *strPassword;

}

@end

ViewController.m

#define testURK [NSURL URLWithString: @”https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=flower&as_filetype=png&imgsz=medium”%5D //2.2

#import “ViewController.h”
#import “WebAPIRequest.h”
#import “SBJson.h”
#import “Database.h”
@implementation ViewController

– (void)viewDidLoad
{
[super viewDidLoad];

strUserName = @”test@gmail.com”;
strPassword = @”test123″;

//Call webservice here

[WebAPIRequest sample:self username:strUserName password:strPassword Tag:1];

}

//Response  here

-(void)setTradeData:(NSString *)message items:(NSString *)items withtag:(int)tag
{

NSLog(@”you get response here :%@”,[items JSONValue]);

NSString *str = [NSString stringWithFormat:@”INSERT INTO login (username,password) VALUES(‘%@’,’%@’)”,strUserName,strPassword];

[Database executeQuery:str];

//you can get response here then after you add the value in database

}

@end

Database.h

#import <Foundation/Foundation.h>
#import <sqlite3.h>

@interface Database : NSObject {

}
+(NSString* )getDatabasePath;
+(NSMutableArray *)executeQuery:(NSString*)str;
+(NSString*)encodedString:(const unsigned char *)ch;
+(BOOL)executeScalarQuery:(NSString*)str;
@end

Database.m

#import “Database.h”
#import <sqlite3.h>

@implementation Database
+(NSString* )getDatabasePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@”database”];

return writableDBPath;

}

+(NSMutableArray *)executeQuery:(NSString*)str{

sqlite3_stmt *statement= nil;
sqlite3 *database;
NSString *strPath = [self getDatabasePath];
NSMutableArray *allDataArray = [[NSMutableArray alloc] init];
if (sqlite3_open([strPath UTF8String],&database) == SQLITE_OK) {
if (sqlite3_prepare_v2(database, [str UTF8String], -1, &statement, NULL) == SQLITE_OK) {

while (sqlite3_step(statement) == SQLITE_ROW) {
NSInteger i = 0;
NSInteger iColumnCount = sqlite3_column_count(statement);
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
while (i< iColumnCount) {
NSString *str = [self encodedString:(const unsigned char*)sqlite3_column_text(statement, i)];

NSString *strFieldName = [self encodedString:(const unsigned char*)sqlite3_column_name(statement, i)];

[dict setObject:str forKey:strFieldName];
i++;
}

[allDataArray addObject:dict];
[dict release];
}
}

sqlite3_finalize(statement);
}
sqlite3_close(database);
return allDataArray;
}
+(NSString*)encodedString:(const unsigned char *)ch
{
NSString *retStr;
if(ch == nil)
retStr = @””;
else
retStr = [NSString stringWithCString:(char*)ch encoding:NSUTF8StringEncoding];
return retStr;
}
+(BOOL)executeScalarQuery:(NSString*)str{

sqlite3_stmt *statement= nil;
sqlite3 *database;
BOOL fRet = NO;
NSString *strPath = [self getDatabasePath];
if (sqlite3_open([strPath UTF8String],&database) == SQLITE_OK) {
if (sqlite3_prepare_v2(database, [str UTF8String], -1, &statement, NULL) == SQLITE_OK) {
if (sqlite3_step(statement) == SQLITE_DONE)
fRet =YES;
}

sqlite3_finalize(statement);
}
sqlite3_close(database);
return fRet;
}
@end

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s