Instagram上的iOS共享:无法保存文件,因为不支持指定的URL类型

时间:2017-01-13 17:39:58

标签: ios swift swift3

我在swift 3 iOS 10.1中使用以下代码在Instagram上分享图像:

func shareOnInstagram(_ photo: UIImage, text: String?) {
    let instagramUrl = URL(string: "instagram://app")!
    if UIApplication.shared.canOpenURL(instagramUrl) {
        let imageData = UIImageJPEGRepresentation(photo, 1.0)!
        let captionString = text ?? ""

        let writePath = URL(string: NSTemporaryDirectory())!.appendingPathComponent("instagram.igo")
        do {
            try imageData.write(to: writePath)
            let documentsInteractionsController = UIDocumentInteractionController(url: writePath)
            documentsInteractionsController.delegate = self
            documentsInteractionsController.uti = "com.instagram.exlusivegram"
            documentsInteractionsController.annotation = ["InstagramCaption": captionString]
            documentsInteractionsController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)
        }catch {
            return
        }
    }else {
        let alertController = UIAlertController(title: "Install Instagram", message: "You need Instagram app installed to use this feature. Do you want to install it now?", preferredStyle: .alert)
        let installAction = UIAlertAction(title: "Install", style: .default, handler: { (action) in
            //redirect to instagram
        })
        alertController.addAction(installAction)

        let laterAction = UIAlertAction(title: "Later", style: .cancel, handler: nil)
        alertController.addAction(laterAction)

        present(alertController, animated: true, completion: nil)
    }
}

try imageData.write(to: writePath)行,它会抛出如下错误:

Error Domain=NSCocoaErrorDomain Code=518 "The file couldn’t be saved because the specified URL type isn’t supported." UserInfo={NSURL=/private/var/mobile/Containers/Data/Application/5B80A983-5571-44A5-80D7-6A7B065800B5/tmp/instagram.igo}

有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:37)

您正在错误地创建URL。变化:

let writePath = URL(string: NSTemporaryDirectory())!.appendingPathComponent("instagram.igo")

为:

let writePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("instagram.igo")

每当您从文件路径创建URL时,都必须使用fileURLWithPath初始值设定项。使用string初始值设定项仅在创建以URLhttpmailto等广告系列开头的tel时有效。< / p>