2014-07-03 40 views
0

我創建了一個應用程序以保存爲csv文件,應用程序在iOS模擬器中同時可以讀寫。當我將應用程序加載到iOS設備時,它不包含數據。在iOS設備上讀取csv文件時出錯

- (IBAction)saveInfo:(id)sender { 
    NSString *resultLine = [NSString stringWithFormat:@"%@,%@,%@\n", 
          self.food.text, 
          self.movies.text, 
          self.channel.text]; 
    NSArray *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *docPath = [path objectAtIndex:0]; 
    //resultView.text = docPath; 

    NSString *filename = [docPath stringByAppendingString:@"result.csv"]; 
    resultView.text = filename; 

    if (![[NSFileManager defaultManager] fileExistsAtPath:filename]) 
    { 
     [[NSFileManager defaultManager] createFileAtPath:filename contents:nil attributes:nil]; 
    } 
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filename]; 
    [fileHandle seekToEndOfFile]; 
    [fileHandle writeData:[resultLine dataUsingEncoding:NSUTF8StringEncoding]]; 
    [fileHandle closeFile]; 
    self.food.text = nil; 
    self.movies.text = nil; 
    self.channel.text =nil; 
    NSLog(@"Info saved"); 


} 


- (IBAction)viewInfo:(id)sender { 
    NSArray *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *docPath = [path objectAtIndex:0]; 
    NSString *filename = [docPath stringByAppendingString:@"result.csv"]; 

    NSString *fileContent=[NSString stringWithContentsOfFile:filename encoding:NSUTF8StringEncoding error:nil]; 

    resultView.text = fileContent; 

} 
+0

請註明你所得到的異常,以及在什麼點你得到它 – ZeMoon

回答

1

您正在錯誤地構建路徑。用途:

NSArray *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docPath = [path objectAtIndex:0]; 
NSString *filename = [docPath stringByAppendinPathComponent:@"result.csv"]; 

你有像<path to app bundle>/Documentsresult.csv的路徑,你不能寫入應用程序捆綁在設備上產生的代碼。

+0

當這個答案通過時輸入完全相同的東西。 +1 – DexterW

2

在按鈕動作U可以寫出下面的代碼也許文件將顯示在我的觀點的正確運行,你應該托盤點.....

NSFileManager *filemgr; 
NSString *dataFile; 
NSString *docsDir; 
NSArray *dirPaths; 

filemgr = [NSFileManager defaultManager]; 

dirPaths = NSSearchPathForDirectoriesInDomains(
               NSDocumentDirectory, NSUserDomainMask, YES); 

docsDir = [dirPaths objectAtIndex:0]; 
dataFile = [docsDir 
      stringByAppendingPathComponent: @"datafile.csv"]; 
NSLog(@"%@",dataFile); 
NSData *data = [filemgr contentsAtPath:dataFile]; 
NSString *[email protected]"----------------\n Full File Data \n ---------------- \n " ; 
fooString = [fooString stringByAppendingString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ]; 
self.FileTextView.text=fooString;