Objective c 在Xcode 11.3中读取文档中的文件失败
当我使用Objective c 在Xcode 11.3中读取文档中的文件失败,objective-c,xcode,objective-c-swift-bridge,Objective C,Xcode,Objective C Swift Bridge,当我使用stringWithContentsOfURL读取文档中的文件时,它失败了 这是Xcode控制台中的错误: Error Domain=NSCOCAERRORDOMAIN Code=256“无法打开文件“1.txt”。“用户信息={NSURL=/var/mobile/Containers/Data/Application/E026973D-11B6-4895-B8FE-7f9fbc11c12/Documents/bbbbb/1.txt}” 这是我的代码: //use objective-
stringWithContentsOfURL
读取文档中的文件时,它失败了
这是Xcode控制台中的错误:
Error Domain=NSCOCAERRORDOMAIN Code=256“无法打开文件“1.txt”。“用户信息={NSURL=/var/mobile/Containers/Data/Application/E026973D-11B6-4895-B8FE-7f9fbc11c12/Documents/bbbbb/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")
您使用了错误的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;
}
您使用了错误的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;
}