0

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")
Cœur
  • 37,241
  • 25
  • 195
  • 267
jansma
  • 1,605
  • 1
  • 15
  • 22

1 Answers1

2

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;
}
vadian
  • 274,689
  • 30
  • 353
  • 361