Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS share on Instagram: The file couldn’t be saved because the specified URL type isn’t supported

Tags:

ios

swift

swift3

I am having following code to share image on instagram in swift 3 iOS 10.1:

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)
    }
}

An at the line try imageData.write(to: writePath), it is throwing error as following:

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}

Can someone help me with this?

like image 866
Rohan Sanap Avatar asked Jan 13 '17 17:01

Rohan Sanap


1 Answers

You are creating your URL incorrectly. Change:

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

to:

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

Whenever you create a URL from a file path you must use the fileURLWithPath initializer. Using the string initializer is only valid when creating a URL that begins with a scheme such as an http, mailto, tel, etc. URLs.

like image 140
rmaddy Avatar answered Nov 15 '22 19:11

rmaddy