我有这段代码:
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有价值:"
/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
有谁知道修理吗?我有文件在这条路上。 我无法重命名我的文件名
答案 0 :(得分:1)
问题是由URL
包含无效字符(即空格)引起的。您需要对URL进行编码以删除无效字符。
let localUrlString = "/Users/imac/Library/Developer/CoreSimulator/Devices/A2B19B93-A0AD-46DF-923F-E18DD76EAC96/data/Containers/Data/Application/A37F7B0E-3B67-42E8-B616-5C3066F5653F/Documents/enb\\g/PDF/MyFile RostiBites2015-ENG new_OK-prev.pdf"
if let localEncodedUrlString = localUrlString.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) {
let localUrl = URL(fileURLWithPath: localEncodedUrlString)
}
您的函数名称非常具有误导性,因为您问题中www
的值显然是本地文件路径,因此要么更改函数名称,要么确实应该从远程URL打开文件,请更改{ {1}}到URL(fileURLWithPath: localEncodedUrlString)
并使用可选绑定来安全地打开可用的初始化程序。
答案 1 :(得分:1)
网址显然是文件系统网址 - 由前导斜杠表示 - 因此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)
}
}