我有这个代码:
func openPDFFromInternet(www: String){
let serwerUrl = ApiConstans.fullPath + "" + www
let url = NSURL(string: www)
print("the url = \(url)")
UIApplication.shared.open(URL(string : www)!)
}
www 具有值(value):“
/Users/imac/Library/Developer/CoreSimulator/Devices/A2B19B93-A0AD-46DF-923F-E18DD76EAC96/data/Containers/Data/Application/A37F7B0E-3B67-42E8-B616-5C3066F5653F/Documents/eng/PDF/MyFile RostiBites2015-ENG new_OK-prev.pdf"
打印返回零。
当我运行这段代码时出现错误:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
有人知道修吗?我在这个路径中有文件。 我无法重命名我的文件名
最佳答案
该 URL 显然是一个文件系统 URL – 由前导斜杠表示 – 因此 API URL(string:
是错误的。您必须使用 URL(fileURLWithPath
百分比隐式转义空格字符。
func openPDFFromInternet(www: String){
let serwerUrl = ApiConstans.fullPath + "" + www
let url = URL(fileURLWithPath : www)
print("the url = \(url)")
UIApplication.shared.open(url)
}
或者如果 URL 可以是本地的或远程的更健壮的方式
func openPDFFromInternet(www: String){
let serwerUrl = ApiConstans.fullPath + "" + www
if www.hasPrefix("/") {
let url = URL(fileURLWithPath : www)
UIApplication.shared.open(url)
} else {
guard let escapedString = www.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed),
let url = URL(string : escapedString) else { return }
UIApplication.shared.open(url)
}
}
关于ios - 文件路径中可选值的解包错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50812887/