New Method For API Call

[[[NSURLSession sharedSession] dataTaskWithRequest:theRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {

NSLog(@”error===> %@”,error);

} else {

NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
recordArr = [[NSMutableArray alloc] initWithArray:[jsonObject valueForKey:@”record”]];
NSLog(@”recordArr===> %@”,recordArr);

 

}
}] resume];

Advertisements

Add Via For Loop with Dictionary

for (int i = 0; i<self.dataArray.count; i++)
{
NSDictionary *innerDic = self.dataArray[i];

NSString *strQuery = [NSString stringWithFormat:@”INSERT INTO main.tblFav (\”memId\”,\”firstname\”,\”fathername\”,\”lastname\”,\”address1\”,\”address2\”,\”area\”,\”city\”,\”native\”,\”phMobile\”,\”phHome\”,\”phOffice\”,\”gender\”,\”dob\”,\”height\”,\”education\”,\”occupation\”,\”srNo\”,\”Cat\”,\”Subcat\”) VALUES (\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”,\”%@\”)”,[innerDic objectForKey:@”Id”],[innerDic objectForKey:@”FirstName”],[innerDic objectForKey:@”MiddleName”],[innerDic objectForKey:@”LastName”],@””,@””,@””,[innerDic objectForKey:@”City”],[innerDic objectForKey:@”Native”],[innerDic objectForKey:@”PhnMobile”],[innerDic objectForKey:@”PhnHome”],[innerDic objectForKey:@”PhnWork”],@””,@””,@””,@””,@””,@””,@”1″,subCat];

[database executeUpdate:strQuery];

}

===================****************====================

NSString *insertSQL = [NSString stringWithFormat:
@”INSERT INTO tblCartList (ProductID,ProductTitle,ProductDate,ProductTime,ProductImage,TotalCoast,Quantity,CartBadgeCount,ProductDetails,ProductPrice) VALUES (\”%@\”, \”%@\”, \”%@\”, \”%@\”, \”%@\”, \”%f\”, \”%@\”, \”%d\”, \”%@\”, \”%@\”)”,strProductID,
lblProductTitle.text,txtDeliveryDt.text,txtDeliveryTime.text, strImagURL , total,
lblQuantity.text,cartbadge,strProductDetails,strProductPrice];

BOOL success=[database executeUpdate:insertSQL];

 

====================******************====================

for (NSDictionary *dictn in taskDetailsArray)
{
if ([[dictn objectForKey:@”TaskTypeName”]isEqualToString:@”Procedure”]){

[ActivityArry addObject:dictn];
}
}

====================******************======================

//Short array and display list as a date Wise…..
for (int i = 0; i<reverseOrder.count; i++) {
//Set date as per Order…..
tmpString = [[reverseOrder objectAtIndex:i] objectForKey:@”ActivityDate”];
if (![arrKeys containsObject:tmpString])
{
[arrKeys addObject:tmpString];
}
}
for (int i=0 ;i<[arrKeys count]; i++)
{
NSMutableArray *arr=[[NSMutableArray alloc]init];
for (int j=0; j<[reverseOrder count]; j++)
{
NSMutableDictionary *dict=[[NSMutableDictionary alloc]initWithDictionary:[arrayData objectAtIndex:j]];
NSString *strDate = [dict objectForKey:@”ActivityDate”];

if ([[arrKeys objectAtIndex:i] isEqual:strDate])
{
[arr addObject:dict];
}
}
[historyDataArray addObject:arr];
}

 

============================================================

– (void)addDataDB{
database=[FMDatabase databaseWithPath:self.path];

if(![database open])
NSLog(@”%@”,[database lastErrorMessage]);

NSString *strQuery;

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

[database open];
NSDictionary *dict = [recordArr objectAtIndex:i];

if ([dict objectForKey:@”name”] == nil && [dict objectForKey:@”sub_cat_id”])
{
NSLog(@”Name not found”);
return;
}
else if ([dict objectForKey:@”sub_cat_id”] == nil)
{
NSLog(@”sub_cat_id not found”);
return;
}

NSString *name = [dict valueForKey:@”name”];
NSString *sub_cat_id = [NSString stringWithFormat:@”%@”,[dict valueForKey:@”sub_cat_id”]];

strQuery = [NSString stringWithFormat:@”INSERT INTO tblEmp (\”Name\”,\”Age\”) VALUES (\”%@\”,\”%@\”)”,name,sub_cat_id];

BOOL success=[database executeUpdate:strQuery];

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

[database close];
}
}

=========

– (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);

NSDictionary *dict = [recordArr objectAtIndex:indexPath.row];

cell.lblTitle.text = [dict valueForKey:@”name”];
return cell;

}

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/&#8221;;
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;
}