ios - 文件路径中可选值的解包错误

标签 ios swift

我有这个代码:

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/

相关文章:

javascript - iPhone Web App Div 标签在 Safari 中加载

ios - 这里 map : How to differentiate between two markers at same location

Swift:为什么不能在扩展中添加商店属性?内存中的存储属性和计算属性有什么不同

ios - <FBGraphUser> 对象数组的 UITableView 滚动索引

ios - 未安装 CocoaPods。跳过 pod 安装

ios - FBRequestConnection 不提供 UI 而 FBDialog 提供

objective-c - 为什么最终二进制文件的大小会比静态库的大小小得多?

json - 如何快速获取特定的json值

ios - 为什么我对两个日期的比较不起作用?

ios - 如何在快速点击按钮时从第二个 View Controller 调用第一个 View Controller 功能?