簡體   English   中英

NSData writeToFile無法正常工作

[英]NSData writeToFile not working

我似乎無法讓nsdata寫入文件。 我有什么想法可能做錯了。 提前致謝。

NSString* filename = @"myfile.txt";

NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:filename];    

if ([fileManager fileExistsAtPath:applicationDocumentsDir])
    NSLog(@"applicationDocumentsDir exists");   // verifies directory exist

NSData *data = [NSData dataWithContentsOfURL:URL];

if (data) {    
     NSString *content = [[NSString alloc]  initWithBytes:[data bytes]
                                                      length:[data length] encoding: NSUTF8StringEncoding];

    NSLog(@"%@", content); // verifies data was downloaded correctly

    NSError* error;
    [data writeToFile:storePath options:NSDataWritingAtomic error:&error];

    if(error != nil)
        NSLog(@"write error %@", error);
}

我一直在收到錯誤

"The operation couldn’t be completed. No such file or directory"

嘗試

NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:@"myfile.txt"];

 if ([[NSFileManager defaultManager] fileExistsAtPath:storePath])
        NSLog(@"applicationDocumentsDir exists");   

要獲得更多信息,您可以使用

將writeToFile:選項:錯誤:

代替

將writeToFile:原子:

但是您需要在執行寫入之前在路徑中創建所有子目錄。 像這樣:

// if the directory does not exist, create it...
if ( [fileManager fileExistsAtPath:dir_path] == NO ) {
    if ( [fileManager createDirectoryAtPath:dir_path withIntermediateDirectories:NO attributes:NULL error:&error] == NO  ) {
        NSLog(@"createDirectoryAtPath failed %@", error);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM