Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // CitiesTableViewController.m
- // JSON_storyboard
- //
- // Created by Sebastiano Scarlata on 25/03/14.
- // Copyright (c) 2014 Innovative Services srl. All rights reserved.
- //
- #import "Tabella_home.h"
- #import "Notizia.h"
- #import "sqlite3.h"
- #import "Dettaglio.h"
- #define getDataURL @"http://192.168.1.43/json_ios/news.php";
- @interface Tabella_home ()
- @end
- @implementation Tabella_home
- @synthesize jsonArray,citiesArray;
- - (id)initWithStyle:(UITableViewStyle)style
- {
- self = [super initWithStyle:style];
- if (self) {
- // Custom initialization
- }
- return self;
- }
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- self.title=@"TITOLO";
- [self retrieveData];
- [self leggodaldb];
- UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
- [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
- [self.tableView addSubview:refreshControl];
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- #pragma mark - Table view data source
- - (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 5;
- return citiesArray.count;
- }
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
- // Configure the cell...
- Notizia * cityObject;
- cityObject = [citiesArray objectAtIndex:indexPath.row];
- cell.textLabel.text = cityObject.titoloNotizia;
- if(cityObject.titoloNotizia.length>=20)
- {
- NSString *mystr=[cityObject.titoloNotizia substringToIndex:19];
- mystr = [mystr stringByAppendingString:@" ..."];
- cell.detailTextLabel.text = mystr;
- }
- else{
- cell.detailTextLabel.text = cityObject.titoloNotizia;
- }
- // cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
- cell.accessoryType = UITableViewCellSeparatorStyleSingleLineEtched;
- // cell.accessoryType = UITableViewCellAccessoryDetailButton;
- return cell;
- }
- - (void)refresh:(UIRefreshControl *)refreshControl {
- [self retrieveData];
- [self leggodaldb];
- NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"Cerco nuove notizie..."];
- NSRange fullRange = NSMakeRange(0, [string length]);
- [string addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:fullRange];
- [string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia" size:17] range:fullRange];
- [refreshControl setAttributedTitle:string];
- [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
- [self setRefreshControl:refreshControl];
- [refreshControl endRefreshing];
- }
- #pragma mark -
- #pragma mark methodi
- -(void)retrieveData
- {
- //SE SONO COLLEGATO, CANCELLO E RISCARICO I DATI
- NSURL *url =[NSURL URLWithString:@"http://192.168.1.133/json_ios/news.php"];
- // NSURL *url = [NSURL URLWithString:@"http://someurl.com"];
- NSURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:4];
- NSHTTPURLResponse *response = nil;
- [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
- if (response == nil) {
- // timed out or failed
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Nessuna connessione ad internet"
- message:@"I contenuti saranno comunque accessibili, ti consigliamo di collegarti ad una rete internet per rimanere aggiornato!"
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [alert show];
- } else {
- // all good
- NSData *data = [NSData dataWithContentsOfURL:url];
- jsonArray = [NSJSONSerialization JSONObjectWithData:data options:(kNilOptions) error:nil];
- citiesArray = [[NSMutableArray alloc]init];
- //INIZIO DICHIARAZIONE DB
- NSString *docsDir;
- NSArray *dirPaths;
- // Get the documents directory
- dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- docsDir = [dirPaths objectAtIndex:0];
- // Build the path to the database file
- databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"notizia.db"]];
- NSFileManager *filemgr = [NSFileManager defaultManager];
- if ([filemgr fileExistsAtPath: databasePath ] == NO)
- {
- const char *dbpath = [databasePath UTF8String];
- if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
- {
- char *errMsg;
- const char *sql_stmt = "CREATE TABLE IF NOT EXISTS notizia (idNotizia INTEGER PRIMARY KEY, titoloNotizia TEXT)";
- if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
- {
- NSLog(@"Failed to create table");
- }
- sqlite3_close(contactDB);
- } else {
- NSLog(@"Failed to open/create database");
- }
- }
- sqlite3_stmt *statement;
- const char *dbpath = [databasePath UTF8String];
- //FINE DICHIARAZIONE DB
- //Loop throughe our jsonArray
- /***********
- **** PULISCO IL DB - INIZIO *****
- *****/
- if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
- {
- NSString *insertSQLFlush = [NSString stringWithFormat: @"DELETE FROM notizia WHERE 1"];
- const char *insert_stmtFlush = [insertSQLFlush UTF8String];
- sqlite3_prepare_v2(contactDB, insert_stmtFlush, -1, &statement, NULL);
- if (sqlite3_step(statement) == SQLITE_DONE)
- {
- NSLog(@"PULITO");
- } else {
- NSLog(@"ERRORE %s",sqlite3_errmsg(contactDB));
- }
- sqlite3_finalize(statement);
- sqlite3_close(contactDB);
- }
- /***********
- **** PULISCO IL DB - FINE *****
- *****/
- for(int i = 0; i<jsonArray.count; i++)
- {
- //CREATE Cityobject
- // NSString *cID = [[jsonArray objectAtIndex:i]objectForKey:@"id"];
- NSString *cIDnotizia = [[jsonArray objectAtIndex:i]objectForKey:@"ID"];
- NSString *ctitolonotizia = [[jsonArray objectAtIndex:i]objectForKey:@"titolo"];
- NSString *cstate = [[jsonArray objectAtIndex:i]objectForKey:@"testo"];
- //ADD the city object to our cities arra
- // ---> [citiesArray addObject:[[Notizia alloc]initWithTitolo:ctitolonotizia andCityState:cstate andIDNotizia:cIDnotizia]];
- // NSLog(@"ID: %@",cIDnotizia);
- // NSLog(@"Titolo: %@",ctitolonotizia);
- // NSLog(@"Testo: %@",cstate);
- // NSLog(@"-----");
- /*********
- ******* INIZIO DB ********
- ******/
- if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
- {
- NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO notizia (idNotizia,titoloNotizia) VALUES (\"%@\", \"%@\")", cIDnotizia,ctitolonotizia];
- NSLog(@"INSERT INTO notizia (idNotizia,titoloNotizia) VALUES (\"%@\", \"%@\")", cIDnotizia,ctitolonotizia);
- const char *insert_stmt = [insertSQL UTF8String];
- sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
- if (sqlite3_step(statement) == SQLITE_DONE)
- {
- NSLog(@"Inserito");
- } else {
- NSLog(@"ERRORE %s",sqlite3_errmsg(contactDB));
- }
- sqlite3_finalize(statement);
- sqlite3_close(contactDB);
- }
- /*********
- ******* FINE DB ********
- ******/
- }
- [self.tableView reloadData];
- }
- /*
- */
- }
- -(void)leggodaldb{
- NSLog(@"ADESSO LEGGO DAL DB");
- NSURL *url =[NSURL URLWithString:@"http://192.168.1.133/json_ios/news.php"];
- // NSURL *url = [NSURL URLWithString:@"http://someurl.com"];
- NSURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:4];
- NSHTTPURLResponse *response = nil;
- [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
- if (response == nil) {
- // timed out or failed
- /*
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Nessuna connessione ad internet"
- message:@"I contenuti saranno comunque accessibili, ti consigliamo di collegarti ad una rete internet per rimanere aggiornato!"
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [alert show];
- */
- } else {
- // all good
- NSData *data = [NSData dataWithContentsOfURL:url];
- jsonArray = [NSJSONSerialization JSONObjectWithData:data options:(kNilOptions) error:nil];
- citiesArray = [[NSMutableArray alloc]init];
- //INIZIO DICHIARAZIONE DB
- NSString *docsDir;
- NSArray *dirPaths;
- // Get the documents directory
- dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- docsDir = [dirPaths objectAtIndex:0];
- // Build the path to the database file
- databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"notizia.db"]];
- NSFileManager *filemgr = [NSFileManager defaultManager];
- if ([filemgr fileExistsAtPath: databasePath ] == NO)
- {
- // NON C'è IL DB
- }
- else
- {
- NSLog(@"ADESSO LEGGO VERAMENTE");
- const char *dbpath = [databasePath UTF8String];
- sqlite3_stmt *statement;
- if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
- {
- NSString *querySQL = [NSString stringWithFormat: @"SELECT * FROM notizia ORDER BY idNotizia DESC"];
- const char *query_stmt = [querySQL UTF8String];
- if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
- {
- //TROVO
- while(SQLITE_ROW == sqlite3_step(statement)) {
- // const unsigned char * txt = sqlite3_column_text(statement, 3); // get 3rd column text
- // NSString* indays = [NSString stringWithCString:txt encoding:NSASCIIStringEncoding];
- NSString *DBidnotizia=[[NSString alloc] initWithUTF8String:(const char*) sqlite3_column_text(statement, 0)];
- NSString *DBtitolonotizia=[[NSString alloc] initWithUTF8String:(const char*) sqlite3_column_text(statement, 1)];
- NSString *cstate =@"...";
- // NSLog(@"%@",DBidnotizia);
- // NSLog(@"%@",DBtitolonotizia);
- // NSLog(@"conta");
- [citiesArray addObject:[[Notizia alloc]initWithTitolo:DBtitolonotizia andCityState:cstate andIDNotizia:DBidnotizia]];
- }
- sqlite3_finalize(statement);
- }
- sqlite3_close(contactDB);
- }
- }
- /*********
- ******* FINE DB ********
- ******/
- }
- [self.tableView reloadData];
- }
- /*
- -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
- {
- UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"CIAO" message:@"CIAO" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
- [alertView show];
- }
- */
- - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
- {
- }
- /*
- // Override to support conditional editing of the table view.
- - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
- {
- // Return NO if you do not want the specified item to be editable.
- return YES;
- }
- */
- /*
- // Override to support editing the table view.
- - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
- {
- if (editingStyle == UITableViewCellEditingStyleDelete) {
- // Delete the row from the data source
- [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
- } else if (editingStyle == UITableViewCellEditingStyleInsert) {
- // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
- }
- }
- */
- /*
- // Override to support rearranging the table view.
- - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
- {
- }
- */
- /*
- // Override to support conditional rearranging of the table view.
- - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
- {
- // Return NO if you do not want the item to be re-orderable.
- return YES;
- }
- */
- /*
- #pragma mark - Navigation
- // In a storyboard-based application, you will often want to do a little preparation before navigation
- - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
- {
- // Get the new view controller using [segue destinationViewController].
- // Pass the selected object to the new view controller.
- }
- */
- @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement