致命错误:在 Instagram 上上传视频网址期间解包可选值时意外发现 nil



我正在尝试在Instagram上上传视频网址。 在搜索了大量代码之后,我终于找到了这段代码。

    let url : NSString = "http://mobmp4.org/files/data/2480/Tutak%20Tutak%20Tutiya%20Title%20Song%20-%20Remix%20-%20Drunx%20-%20Mp4.mp4"
    let urlStr : NSString = url.addingPercentEscapes(using: String.Encoding.utf8.rawValue)! as NSString
    let videoURL : NSURL = NSURL(string: urlStr as String)!
    print(videoURL)
    let caption = "Some Preloaded Caption"
    //let movieURL = NSURL.fileURL(withPath: moviePath, isDirectory: false)
    let library = ALAssetsLibrary()

    library.writeVideoAtPath(toSavedPhotosAlbum: videoURL as URL!) { (newURL, error) in
        let instagramURL = NSURL(string: "instagram://library?AssetPath=(videoURL)&InstagramCaption=(caption.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed))")!
        if UIApplication.shared.canOpenURL(instagramURL as URL) {
            UIApplication.shared.openURL(instagramURL as URL)
        }
    }

但是我在 InstagramURL 变量上收到诸如"致命错误:在解开可选值时意外发现 nil"之类的错误。

您应该安全地取消可选值的包装,例如:

if let instagramURL = URL(string: "instagram://library?AssetPath=(videoURL)&InstagramCaption=(caption.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed))") {
    if UIApplication.shared.canOpenURL(instagramURL) {
        UIApplication.shared.openURL(instagramURL)
    }
    else{
        //To handle the situation that app Instagram is not installed.
    }
}
else{
     //To handle the bad url.
}

这里是网址编码:Objective-C 和 Swift URL 编码

最新更新