WebService and Database…..

FMDB Class=>https://github.com/appcoda/FMDBDemo

AppDelegate.h

-(NSString *)encodesmiliesandstring:(NSString *)convertstring;
-(NSString *)encodeUrl:(NSString *)string;

AppDelegate.m

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

NSString *documentpath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(@”documentpath : %@”,documentpath);

NSString *foofile=[documentpath stringByAppendingPathComponent:@”simple.sqlite”];

NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:foofile forKey:@”databasePath”];
[defaults synchronize];

BOOL fileexist=[[NSFileManager defaultManager]fileExistsAtPath:foofile];

if(!fileexist)
{
NSString *sourcepath=[[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:@”simple.sqlite”];
NSError *error=nil;

if([[NSFileManager defaultManager]copyItemAtPath:sourcepath toPath:foofile error:&error])
{
NSLog(@”default file copy….”);
}
else
{
NSLog(@”Error descriptin—–>%@\n”,[error localizedDescription]);
NSLog(@”Error reason—->%@”,[error localizedFailureReason]);
}
}

}

-(NSString *)encodeUrl:(NSString *)string
{
NSString *convertedstring=[NSString stringWithString:string];
convertedstring=[convertedstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return convertedstring;
}

-(NSString *)encodesmiliesandstring:(NSString *)convertstring
{
NSString *convertedstring=[NSString stringWithString:convertstring];
convertedstring=[convertedstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return convertedstring;
}

ViewController.h

#import “AppDelegate.h”
#import “FMDatabase.h”

@interface MenuCell : UITableViewCell

@property (strong , nonatomic)IBOutlet UILabel *lblTitle;
@property (nonatomic , weak) IBOutlet UIImageView *imgLogo;

@end

@interface ViewController : UIViewController{

IBOutlet UITableView *tblData;
NSMutableArray *recordArr;
AppDelegate *app;
FMDatabase *database;
NSUserDefaults *defaults;

}
@property(strong,nonatomic)NSString *path;
@property(strong,nonatomic)NSString *msg;

ViewController.m

@implementation MenuCell

@synthesize lblTitle,imgLogo;
@end

– (void)viewDidLoad {
[super viewDidLoad];
defaults=[NSUserDefaults standardUserDefaults];
self.path=[defaults stringForKey:@”databasePath”];
app = (AppDelegate *)[[UIApplication sharedApplication]delegate];

//NSString * url=[NSString stringWithFormat:@”%@api/user/login?email=%@&password=%@”,BaseUrl,txtEmail.text,txtPwd.text]; //LIVE

NSString *strURL = @”http://ec2-35-164-90-67.us-west-2.compute.amazonaws.com/”;
strURL = [NSString stringWithFormat:@”%@api/getSubCategories?category_id=%@”,strURL,@”1″];

NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[app encodesmiliesandstring:strURL]] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:9000];
[theRequest setHTTPMethod:@”POST”];
[theRequest addValue:@”application/json” forHTTPHeaderField:@”Content-Type”];
NSLog(@”webservice called for post is %@”,theRequest);

[NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue]completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{

if ([(NSHTTPURLResponse *)response statusCode]==200)
{
NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

NSNumber *resultStr = [jsonObject objectForKey:@”status”];

if ([resultStr intValue] == 1){
NSLog(@”SUCCESS”);

recordArr = [[[NSMutableArray alloc] initWithArray:[jsonObject valueForKey:@”record”]] valueForKey:@”name”];
[self addDataDB];
[tblData reloadData];

}
else{
}
}
else
{
UIAlertController *alert=[UIAlertController alertControllerWithTitle:@”Alert!” message:@”Could not connect to the network. Please try again in a few seconds.” preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *no = [UIAlertAction actionWithTitle:@”Ok” style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:no];
[self.navigationController presentViewController:alert animated:YES completion:nil];
}
}];
}

 

– (void)addDataDB{
database=[FMDatabase databaseWithPath:self.path];
if(![database open])
NSLog(@”%@”,[database lastErrorMessage]);

NSString *strQuery;

for (int i = 0; i<recordArr.count; i++) {

NSMutableDictionary *dict=[[recordArr objectAtIndex:i] mutableCopy];
NSLog(@”dbArryData===> %@”,dict);
strQuery = [NSString stringWithFormat:@”INSERT INTO tblEmp (\”Name\”) VALUES (\”%@\”)”,[[recordArr objectAtIndex:i] mutableCopy]];
BOOL success=[database executeUpdate:strQuery];

if(success){
self.msg=@”record insertd successfully”;
NSLog(@”record insertd successfully”);
}
else{
self.msg=[database lastErrorMessage];
}
}

[database close];
}

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

// Return the number of sections.
return 1;
}

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

// Return the number of rows in the section.
return recordArr.count;

}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

NSString * identifier=[NSString stringWithFormat:@”MenuCell”];
MenuCell *cell=(MenuCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
if(cell == nil){
cell=[[MenuCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier ];
}
NSLog(@”recordArr===> %@”,recordArr);
cell.lblTitle.text = [recordArr objectAtIndex:indexPath.row];
return cell;

}

– (IBAction)saveInDataBase:(id)sender{
SecondViewController *objSecondVC = [self.storyboard instantiateViewControllerWithIdentifier:@”SecondViewController”];
[self.navigationController pushViewController:objSecondVC animated:YES];
}

SecondViewController.h

#import “FMDatabase.h”

@interface MenuDisplayCell : UITableViewCell

@property (strong , nonatomic)IBOutlet UILabel *lblTitle;
@property (nonatomic , weak) IBOutlet UIImageView *imgLogo;

@end

@interface SecondViewController : UIViewController{

NSMutableArray *dbArryData;
FMDatabase *database;
NSUserDefaults *defaults;
IBOutlet UITableView *tblDisplyDB;

}
@property(strong,nonatomic)NSString *path;
@property(strong,nonatomic)NSString *msg;
@end

SecondViewController.m

@implementation MenuDisplayCell

@synthesize lblTitle,imgLogo;
@end

– (void)viewDidLoad {
[super viewDidLoad];

defaults=[NSUserDefaults standardUserDefaults];
self.path=[defaults stringForKey:@”databasePath”];

database=[FMDatabase databaseWithPath:self.path];
if(![database open])
NSLog(@”%@”,[database lastErrorMessage]);

NSString *query=[NSString stringWithFormat:@”select * from tblEmp”];
FMResultSet *result=[database executeQuery:query];

dbArryData=[[NSMutableArray alloc]init];

while([result next])
{

NSDictionary *groupDict=@{
@”Name”:[result stringForColumn:@”Name”]!=nil?[result stringForColumn:@”Name”]:@””,

};

[dbArryData addObject:groupDict];
}
NSLog(@”arrDBCartDetails===> %@”,dbArryData);

}

– (IBAction)backBtnClick:(id)sender{
[self.navigationController popViewControllerAnimated:YES];
}

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return dbArryData.count;
}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

NSString * identifier=[NSString stringWithFormat:@”MenuDisplayCell”];
MenuDisplayCell *cell=(MenuDisplayCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
if(cell == nil){
cell=[[MenuDisplayCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier ];
}
cell.lblTitle.text = [[dbArryData valueForKey:@”Name”] objectAtIndex:indexPath.row];
return cell;
}

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