Read file in document failed in Xcode 11.3

89 Views Asked by At

When I read file in document using stringWithContentsOfURL it failed

this is error in Xcode console:

Error Domain=NSCocoaErrorDomain Code=256 "The file “1.txt” couldn’t be opened." UserInfo={NSURL=/var/mobile/Containers/Data/Application/E026973D-11B6-4895-B8FE-7F9FBCC11C12/Documents/bbbb/1.txt}

this is my code:

 //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")
1

There are 1 best solutions below

0
vadian On

You are using the wrong API:

URLWithString is for URLs including the scheme (file:// or https://), for file system paths you have to use fileURLWithPath.

However it's highly recommended to use always the URL related API to build paths

+ (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;
}