0

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

这是 Xcode 控制台中的错误:

错误域 = NSCocoaErrorDomain 代码 = 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")
4

1 回答 1

2

您使用了错误的 API:

URLWithString适用于包含方案(file://https://)的 URL,适用于您必须使用的文件系统路径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;
}
于 2019-12-24T11:05:47.020 回答