0

I am trying to upload video url on Instagram. after searching lots of code finally i comes to this code.

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

but i got error like "fatal error: unexpectedly found nil while unwrapping an Optional value" at instagramURL variable.

Krunal Patel
  • 1,649
  • 1
  • 14
  • 22
  • in which line your code broken ? – KKRocks May 16 '17 at 06:56
  • let instagramURL = NSURL(string: "instagram://library?AssetPath=\(videoURL)&InstagramCaption=\(caption.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed))")! – Krunal Patel May 16 '17 at 06:58
  • i can successfully open Library or camera on instagram by this code but i want to upload video which i have as string (like somthig.mp4). – Krunal Patel May 16 '17 at 10:06

1 Answers1

1

You should unbox the optional value safely, like:

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

Here for url encoding: Objective-C and Swift URL encoding

Community
  • 1
  • 1
Yun CHEN
  • 6,450
  • 3
  • 30
  • 33
  • i got a result like this after printing instagramURL, "instagram://library?AssetPath=http:%2F%2Fmobmp4.org%2Ffiles%2Fdata%2F2480%2FTutak%2520Tutak%2520Tutiya%2520Title%2520Song%2520-%2520Remix%2520-%2520Drunx%2520-%2520Mp4.mp4&InstagramCaption=Some%20Preloaded%20Caption" – Krunal Patel May 16 '17 at 10:02
  • i can successfully open Library or camera on instagram by this code but i want to upload video which i have as string (like somthig.mp4). – Krunal Patel May 16 '17 at 10:06