【问题标题】:Read file in document failed in Xcode 11.3在 Xcode 11.3 中读取文档中的文件失败
【发布时间】:2019-12-24 10:53:28
【问题描述】:

当我使用 stringWithContentsOfURL 读取文档中的文件时,它失败了

这是 Xcode 控制台中的错误:

Error Domain=NSCocoaErrorDomain Code=256 "无法打开文件“1.txt”。" UserInfo={NSURL=/var/mobile/Containers/Data/Application/E026973D-11B6-4895-B8FE-7F9FBCC11C12/Documents/bbbb/1.txt}

这是我的代码:

 //use objective-c
 +(NSString * )loadDataFromDocumentDirectory:(NSString *)path andSubDirectory:(NSString *)subdirectory {
    path = [self stripSlashIfNeeded:path];
    subdirectory = [self stripSlashIfNeeded:subdirectory];

    // Create generic beginning to file save path
    NSMutableString *savePath = [[NSMutableString alloc] initWithFormat:@"%@/",[self applicationDocumentsDirectory].path];
    [savePath appendString:subdirectory];
    [savePath appendString:@"/"];

    // Add requested save path
    NSError *err = nil;
    [savePath appendString:path];
    NSURL *fileURL = [NSURL URLWithString:savePath];
    NSString *loadStr = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:&err]  ;
    if (err) NSLog(@"load error : %@", err);

    return loadStr;
}

//use swift
let loadData = FileSave.loadData(fromDocumentDirectory: "1.txt", andSubDirectory: "bbbb")

【问题讨论】:

    标签: objective-c xcode objective-c-swift-bridge


    【解决方案1】:

    您使用了错误的 API:

    URLWithString 用于包含方案的 URL(file://https://),对于文件系统路径,您必须使用 fileURLWithPath

    但强烈建议始终使用与 URL 相关的 API 来构建路径

    + (NSString * )loadDataFromDocumentDirectory:(NSString *)path andSubDirectory:(NSString *)subdirectory {
        // path = [self stripSlashIfNeeded:path]; not needed
        // subdirectory = [self stripSlashIfNeeded:subdirectory]; not needed
        // Create generic beginning to file save path
        NSURL *saveURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:subdirectory];
    
        // Add requested save path
        NSError *err = nil;
        NSURL *fileURL = [saveURL URLByAppendingPathComponent:path];
        NSString *loadStr = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:&err]  ;
        if (err) NSLog(@"load error : %@", err);
    
        return loadStr;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多