2014-01-06 103 views
0

我的項目工作文件,當我下載並列出保存的文件到tableView。但是當我列出文件到tableView時(見圖),我遇到了文件名的問題。下載並保存文件到tableview

這裏是我的cellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"]; 
    } 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil]; 
    cell.textLabel.text = [documentsDirectory stringByAppendingString:[filePathsArray objectAtIndex:indexPath.row]]; 
    return cell; 
} 

另一個我想下載不同的文件不同的擴展名,並與原來的文件保存它,但我的代碼僅保存我設置文件名。 這裏是我的代碼:

- (IBAction)download { 

// NSString* fileToSaveTo = @"file"; 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     NSLog(@"Downloading Started"); 
     NSString *urlToDownload = @"http://chingfong.com/Icon.png"; 
     NSURL *url = [NSURL URLWithString:urlToDownload]; 
     NSData *urlData = [NSData dataWithContentsOfURL:url]; 
     if (urlData) 
     { 
      NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
      NSString *documentsDirectory = [paths objectAtIndex:0]; 

      NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"Image.png"]; 

      //saving is done on main thread 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       [urlData writeToFile:filePath atomically:YES]; 
       NSLog(@"File Saved !"); 
      }); 
     } 

    }); 

} 
+0

這是什麼問題?你不喜歡什麼工作? – Wain

+0

我想tableView只顯示「filename.extension」並不是所有的目錄。我想用不同的擴展名下載不同的文件。在我的項目中,當我下載一個PFD文件,但它保存與123.png –

+0

爲什麼你爲什麼使用'documentsDirectory stringByAppendingString ...' – Wain

回答

0

A.

不要使用documentsDirectory stringByAppendingString創建單元格文本,只是使用的文件名。

B.

不要硬代碼保存的文件名,而是使用:

NSString *fileName = [urlToDownload lastPathComponent]; 
+0

所以我需要刪除NSString * filePath = [NSString stringWithFormat:@「%@ /%@」,documentsDirectory,@「Image.png」];並添加你的代碼? –

+0

您需要將'Image.png'部分更改爲使用'fileName'。你也應該使用'stringByAppendingPathComponent:'。 – Wain

+0

好的,謝謝你,它現在工作 –