Come leggere un file da una applicazione per iPhone

iPhone Soft! Commenta l'articolo

Prima di tutto aggiungiamo il file nella cartella resources e poi leggiamo il contenuto con il seguente codice, assumendo miofile.txt il file da leggere:

   1. NSString *filePath = [[NSBundle mainBundle] pathForResource:@"miofile" ofType:@"txt"];  
   2. NSData *myData = [NSData dataWithContentsOfFile:filePath];  
   3. if (myData) {  
   4.     // qualcosa 
   5. }  


Adesso con questo esempio possiamo pensare di far leggere un file di help all’interno di una uiwebview:

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"helpfile" ofType:@"htm"];  
 NSData *htmlData = [NSData dataWithContentsOfFile:filePath];  
 if (htmlData) {  
     [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://softeoscar.altervista.org"]];  
 } 

Stesso discorso vale per un file pdf:

 NSString* filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"pdf"];
 NSData* data = [NSData dataWithContentsOfFile:filePath];
 if (htmlData) {  
     [webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://softeoscar.altervista.org"]];  
 } 
 

Come ultimo esempio vediamo come leggere un file di testo, metterlo in una stringa e farlo leggere in un componente uitextview:

NSError *error = nil;
 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"fileditesto" ofType:@"txt"];  
 if (filePath) {  
     NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSASCIIStringEncoding error:&error];  
     if (myText) {  
         textView.text= myText;  
     }  
} 

Questi sono alcuni degli esempi per leggere un file, ma gli usi che se ne possono fare sono innumerevoli. Buon lavoro.

Scrivi un Commento

Home | Graffiti e Disegni | Educazione | Chi siamo | Blog | Progetti | Contatti
RSS Feed Comments RSS Accedi