[英]Read file in document failed in Xcode 11.3
When I read file in document using stringWithContentsOfURL
it failed当我使用
stringWithContentsOfURL
读取文档中的文件stringWithContentsOfURL
它失败了
this is error in Xcode console:这是 Xcode 控制台中的错误:
Error Domain=NSCocoaErrorDomain Code=256 "The file “1.txt” couldn't be opened."
错误域=NSCocoaErrorDomain 代码=256“无法打开文件“1.txt”。 UserInfo={NSURL=/var/mobile/Containers/Data/Application/E026973D-11B6-4895-B8FE-7F9FBCC11C12/Documents/bbbb/1.txt}
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")
You are using the wrong API:您使用了错误的 API:
URLWithString
is for URLs including the scheme ( file://
or https://
), for file system paths you have to use fileURLWithPath
. URLWithString
用于包含方案( file://
或https://
)的 URL,对于文件系统路径,您必须使用fileURLWithPath
。
However it's highly recommended to use always the URL related API to build paths但是强烈建议始终使用与 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.