I have Obj-C code that looks like this
NSURL * url = [[NSBundle mainBundle] URLForResource:@"MyFile" withExtension:@"txt"];
NSError * err = nil;
NSString * string = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&err];
This code is working properly. I need to convert it to Swift one, so I did it like this
func getContentOfUrl(by fileName: String) -> String? {
var result: String?
guard let pathToFile = Bundle.main.path(forResource: fileName, ofType: "txt")
else {
return nil
}
do {
result = try String(contentsOf: URL(string: pathToFile)!, encoding: String.Encoding.utf8)
}
catch let err{
}
return result
}
And I get an error in the catch block
Attempt to get content of URL FAILED, error: Error Domain=NSCocoaErrorDomain Code=256 "The file “MyFile.txt” couldn’t be opened." UserInfo={NSURL=/private/var/containers/Bundle/Application/63FB01-F11-411-B93-6578DEF57B/MyApp.app/MyFile.txt}
what am I doing wrong?
guard let fileURL = Bundle.main.url(forResource: fileName, ofType: "txt")and then then use this url rather than that path, e.g.,String(contentsOf: fileURL, encoding: .utf8).URL(string:. This is the reason of the error. The proper API isURL(fileURLWithPath. And – as already pointed out –URLForResource:withExtension:exists also in Swift.contentsOf: urlAPIs on String, Data, NSDictionary, NSArray, etc. They're synchronous and can block for awhile.