Advertisement
Guest User

Untitled

a guest
Mar 28th, 2014
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  CitiesTableViewController.m
  3. //  JSON_storyboard
  4. //
  5. //  Created by Sebastiano Scarlata on 25/03/14.
  6. //  Copyright (c) 2014 Innovative Services srl. All rights reserved.
  7. //
  8.  
  9. #import "Tabella_home.h"
  10. #import "Notizia.h"
  11. #import "sqlite3.h"
  12. #import "Dettaglio.h"
  13.  
  14. #define getDataURL @"http://192.168.1.43/json_ios/news.php";
  15.  
  16.  
  17.  
  18. @interface Tabella_home ()
  19.  
  20.  
  21. @end
  22.  
  23. @implementation Tabella_home
  24.  
  25. @synthesize jsonArray,citiesArray;
  26.  
  27.  
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
  34. - (id)initWithStyle:(UITableViewStyle)style
  35. {
  36.     self = [super initWithStyle:style];
  37.     if (self) {
  38.         // Custom initialization
  39.     }
  40.     return self;
  41. }
  42.  
  43. - (void)viewDidLoad
  44. {
  45.     [super viewDidLoad];
  46.    
  47.     self.title=@"TITOLO";
  48.     [self retrieveData];
  49.    
  50.     [self leggodaldb];
  51.    
  52.    
  53.     UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
  54.     [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
  55.    
  56.     [self.tableView addSubview:refreshControl];
  57.    
  58.    
  59. }
  60.  
  61. - (void)didReceiveMemoryWarning
  62. {
  63.     [super didReceiveMemoryWarning];
  64.     // Dispose of any resources that can be recreated.
  65. }
  66.  
  67. #pragma mark - Table view data source
  68.  
  69. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  70. {
  71.    
  72.     // Return the number of sections.
  73.     return 1;
  74. }
  75.  
  76. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  77. {
  78.     // Return the number of rows in the section.
  79.     //return 5;
  80.   return citiesArray.count;
  81. }
  82.  
  83. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  84. {
  85.    
  86.     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
  87.  
  88.     // Configure the cell...
  89.     Notizia * cityObject;
  90.     cityObject = [citiesArray objectAtIndex:indexPath.row];
  91.    
  92.     cell.textLabel.text = cityObject.titoloNotizia;
  93.    
  94.     if(cityObject.titoloNotizia.length>=20)
  95.     {
  96.     NSString *mystr=[cityObject.titoloNotizia substringToIndex:19];
  97.         mystr = [mystr stringByAppendingString:@" ..."];
  98.    cell.detailTextLabel.text = mystr;
  99.     }
  100.     else{
  101.       cell.detailTextLabel.text = cityObject.titoloNotizia;
  102.     }
  103.    
  104.    
  105.     // cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  106.     cell.accessoryType = UITableViewCellSeparatorStyleSingleLineEtched;
  107.     // cell.accessoryType = UITableViewCellAccessoryDetailButton;
  108.  
  109.     return cell;
  110. }
  111.  
  112. - (void)refresh:(UIRefreshControl *)refreshControl {
  113.    
  114.     [self retrieveData];
  115.    
  116.     [self leggodaldb];
  117.    
  118.     NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"Cerco nuove notizie..."];
  119. NSRange fullRange = NSMakeRange(0, [string length]);
  120.     [string addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:fullRange];
  121.     [string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia" size:17] range:fullRange];
  122.     [refreshControl setAttributedTitle:string];
  123.     [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
  124.     [self setRefreshControl:refreshControl];
  125.    
  126.     [refreshControl endRefreshing];
  127. }
  128.  
  129.  
  130. #pragma mark -
  131. #pragma mark methodi
  132.  
  133.  
  134. -(void)retrieveData
  135. {
  136.     //SE SONO COLLEGATO, CANCELLO E RISCARICO I DATI
  137.    
  138.     NSURL *url =[NSURL URLWithString:@"http://192.168.1.133/json_ios/news.php"];
  139.    
  140.     //  NSURL *url = [NSURL URLWithString:@"http://someurl.com"];
  141.     NSURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:4];
  142.     NSHTTPURLResponse *response = nil;
  143.     [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
  144.     if (response == nil) {
  145.         // timed out or failed
  146.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Nessuna connessione ad internet"
  147.                                                         message:@"I contenuti saranno comunque accessibili, ti consigliamo di collegarti ad una rete internet per rimanere aggiornato!"
  148.                                                        delegate:nil
  149.                                               cancelButtonTitle:@"OK"
  150.                                               otherButtonTitles:nil];
  151.         [alert show];
  152.        
  153.     } else {
  154.         // all good
  155.        
  156.         NSData *data = [NSData dataWithContentsOfURL:url];
  157.         jsonArray = [NSJSONSerialization JSONObjectWithData:data options:(kNilOptions) error:nil];
  158.         citiesArray = [[NSMutableArray alloc]init];
  159.        
  160.         //INIZIO DICHIARAZIONE DB
  161.         NSString *docsDir;
  162.         NSArray *dirPaths;
  163.         // Get the documents directory
  164.         dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  165.         docsDir = [dirPaths objectAtIndex:0];
  166.         // Build the path to the database file
  167.         databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"notizia.db"]];
  168.         NSFileManager *filemgr = [NSFileManager defaultManager];
  169.         if ([filemgr fileExistsAtPath: databasePath ] == NO)
  170.         {
  171.             const char *dbpath = [databasePath UTF8String];
  172.             if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
  173.             {
  174.                 char *errMsg;
  175.                 const char *sql_stmt = "CREATE TABLE IF NOT EXISTS notizia (idNotizia INTEGER PRIMARY KEY, titoloNotizia TEXT)";
  176.                  if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
  177.                 {
  178.                     NSLog(@"Failed to create table");
  179.                 }
  180.                 sqlite3_close(contactDB);
  181.                
  182.             } else {
  183.                     NSLog(@"Failed to open/create database");
  184.             }
  185.         }
  186.        
  187.         sqlite3_stmt    *statement;
  188.         const char *dbpath = [databasePath UTF8String];
  189.         //FINE DICHIARAZIONE DB
  190.         //Loop throughe our jsonArray
  191.        
  192.         /***********
  193.          **** PULISCO IL DB - INIZIO *****
  194.          *****/
  195.         if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
  196.         {
  197.             NSString *insertSQLFlush = [NSString stringWithFormat: @"DELETE FROM notizia WHERE 1"];
  198.            
  199.             const char *insert_stmtFlush = [insertSQLFlush UTF8String];
  200.            sqlite3_prepare_v2(contactDB, insert_stmtFlush, -1, &statement, NULL);
  201.             if (sqlite3_step(statement) == SQLITE_DONE)
  202.             {
  203.                 NSLog(@"PULITO");
  204.             } else {
  205.                 NSLog(@"ERRORE %s",sqlite3_errmsg(contactDB));
  206.             }
  207.             sqlite3_finalize(statement);
  208.             sqlite3_close(contactDB);
  209.         }
  210.         /***********
  211.          **** PULISCO IL DB - FINE *****
  212.          *****/
  213.        
  214.         for(int i = 0; i<jsonArray.count; i++)
  215.         {
  216.             //CREATE Cityobject
  217.            
  218.             // NSString *cID = [[jsonArray objectAtIndex:i]objectForKey:@"id"];
  219.             NSString *cIDnotizia = [[jsonArray objectAtIndex:i]objectForKey:@"ID"];
  220.             NSString *ctitolonotizia = [[jsonArray objectAtIndex:i]objectForKey:@"titolo"];
  221.             NSString *cstate = [[jsonArray objectAtIndex:i]objectForKey:@"testo"];
  222.            
  223.            
  224.            
  225.            
  226.            
  227.            
  228.            
  229.            
  230.            
  231.            
  232.            
  233.            
  234.             //ADD the city object to our cities arra
  235.     // --->        [citiesArray addObject:[[Notizia alloc]initWithTitolo:ctitolonotizia andCityState:cstate andIDNotizia:cIDnotizia]];
  236.             //    NSLog(@"ID: %@",cIDnotizia);
  237.            //    NSLog(@"Titolo: %@",ctitolonotizia);
  238.             //    NSLog(@"Testo: %@",cstate);
  239.             //    NSLog(@"-----");
  240.            
  241.            
  242.            
  243.             /*********
  244.              ******* INIZIO DB ********
  245.              ******/
  246.            
  247.            
  248.             if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
  249.             {
  250.                 NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO notizia (idNotizia,titoloNotizia) VALUES (\"%@\", \"%@\")", cIDnotizia,ctitolonotizia];
  251.                
  252.                 NSLog(@"INSERT INTO notizia (idNotizia,titoloNotizia) VALUES (\"%@\", \"%@\")", cIDnotizia,ctitolonotizia);
  253.                 const char *insert_stmt = [insertSQL UTF8String];
  254.                
  255.                 sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
  256.                 if (sqlite3_step(statement) == SQLITE_DONE)
  257.                 {
  258.                     NSLog(@"Inserito");
  259.                 } else {
  260.                     NSLog(@"ERRORE %s",sqlite3_errmsg(contactDB));
  261.                 }
  262.                 sqlite3_finalize(statement);
  263.                 sqlite3_close(contactDB);
  264.             }
  265.            
  266.            
  267.            
  268.            
  269.            
  270.             /*********
  271.              ******* FINE DB ********
  272.              ******/
  273.            
  274.            
  275.         }
  276.        
  277.         [self.tableView reloadData];
  278.    
  279.     }
  280.    
  281.    
  282.     /*
  283.      
  284.      
  285.      */
  286.    
  287. }
  288.  
  289. -(void)leggodaldb{
  290.     NSLog(@"ADESSO LEGGO DAL DB");
  291.    
  292.    
  293.     NSURL *url =[NSURL URLWithString:@"http://192.168.1.133/json_ios/news.php"];
  294.    
  295.     //  NSURL *url = [NSURL URLWithString:@"http://someurl.com"];
  296.     NSURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:4];
  297.     NSHTTPURLResponse *response = nil;
  298.     [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
  299.     if (response == nil) {
  300.         // timed out or failed
  301.         /*
  302.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Nessuna connessione ad internet"
  303.                                                         message:@"I contenuti saranno comunque accessibili, ti consigliamo di collegarti ad una rete internet per rimanere aggiornato!"
  304.                                                        delegate:nil
  305.                                               cancelButtonTitle:@"OK"
  306.                                               otherButtonTitles:nil];
  307.         [alert show];
  308.         */
  309.     } else {
  310.         // all good
  311.        
  312.         NSData *data = [NSData dataWithContentsOfURL:url];
  313.         jsonArray = [NSJSONSerialization JSONObjectWithData:data options:(kNilOptions) error:nil];
  314.         citiesArray = [[NSMutableArray alloc]init];
  315.        
  316.         //INIZIO DICHIARAZIONE DB
  317.         NSString *docsDir;
  318.         NSArray *dirPaths;
  319.         // Get the documents directory
  320.         dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  321.         docsDir = [dirPaths objectAtIndex:0];
  322.         // Build the path to the database file
  323.         databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"notizia.db"]];
  324.         NSFileManager *filemgr = [NSFileManager defaultManager];
  325.         if ([filemgr fileExistsAtPath: databasePath ] == NO)
  326.         {
  327.           // NON C'è IL DB
  328.         }
  329.         else
  330.         {
  331.             NSLog(@"ADESSO LEGGO VERAMENTE");
  332.            
  333.            
  334.             const char *dbpath = [databasePath UTF8String];
  335.             sqlite3_stmt    *statement;
  336.            
  337.             if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
  338.             {
  339.                 NSString *querySQL = [NSString stringWithFormat: @"SELECT * FROM notizia ORDER BY idNotizia DESC"];
  340.                
  341.                 const char *query_stmt = [querySQL UTF8String];
  342.                
  343.                 if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
  344.                 {
  345.                         //TROVO
  346.                         while(SQLITE_ROW == sqlite3_step(statement)) {
  347.                            // const unsigned char * txt = sqlite3_column_text(statement, 3); // get 3rd column text
  348.                           //  NSString* indays = [NSString stringWithCString:txt encoding:NSASCIIStringEncoding];
  349.                            
  350.                             NSString *DBidnotizia=[[NSString alloc] initWithUTF8String:(const char*) sqlite3_column_text(statement, 0)];
  351.                            
  352.                             NSString *DBtitolonotizia=[[NSString alloc] initWithUTF8String:(const char*) sqlite3_column_text(statement, 1)];
  353.                            
  354.                             NSString *cstate =@"...";
  355.                            
  356.                            // NSLog(@"%@",DBidnotizia);
  357.                            // NSLog(@"%@",DBtitolonotizia);
  358.                            // NSLog(@"conta");
  359.                            
  360.                             [citiesArray addObject:[[Notizia alloc]initWithTitolo:DBtitolonotizia andCityState:cstate andIDNotizia:DBidnotizia]];
  361.                            
  362.                            
  363.                         }
  364.                    
  365.                     sqlite3_finalize(statement);
  366.                 }
  367.                 sqlite3_close(contactDB);
  368.             }
  369.            
  370.            
  371.            
  372.            
  373.         }
  374.        
  375.        
  376.            
  377.            
  378.            
  379.             /*********
  380.              ******* FINE DB ********
  381.              ******/
  382.            
  383.            
  384.         }
  385.        
  386.         [self.tableView reloadData];
  387. }
  388.  
  389. /*
  390. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  391. {
  392.    
  393.     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"CIAO" message:@"CIAO" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
  394.    
  395.     [alertView show];
  396. }
  397. */
  398. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  399. {
  400.    
  401. }
  402.  
  403.  
  404.  
  405. /*
  406.  // Override to support conditional editing of the table view.
  407.  - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  408.  {
  409.  // Return NO if you do not want the specified item to be editable.
  410.  return YES;
  411.  }
  412.  */
  413.  
  414. /*
  415.  // Override to support editing the table view.
  416.  - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  417.  {
  418.  if (editingStyle == UITableViewCellEditingStyleDelete) {
  419.  // Delete the row from the data source
  420.  [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
  421.  } else if (editingStyle == UITableViewCellEditingStyleInsert) {
  422.  // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
  423.  }
  424.  }
  425.  */
  426.  
  427. /*
  428.  // Override to support rearranging the table view.
  429.  - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
  430.  {
  431.  }
  432.  */
  433.  
  434. /*
  435.  // Override to support conditional rearranging of the table view.
  436.  - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
  437.  {
  438.  // Return NO if you do not want the item to be re-orderable.
  439.  return YES;
  440.  }
  441.  */
  442.  
  443. /*
  444.  #pragma mark - Navigation
  445.  
  446.  // In a storyboard-based application, you will often want to do a little preparation before navigation
  447.  - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  448.  {
  449.  // Get the new view controller using [segue destinationViewController].
  450.  // Pass the selected object to the new view controller.
  451.  }
  452.  */
  453.  
  454. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement