2

I am trying to download youtube video in my app and for that I used THIS and library included in that answer but my app is crashing with error :

fatal error: unexpectedly found nil while unwrapping an Optional value

Here is my swift code:

import UIKit

class ViewController: UIViewController {

    let videoID = "hS5CfP8n_js"
    var extractor = LBYouTubeExtractor()

    override func viewDidLoad() {
        super.viewDidLoad()

    }
    @IBAction func start(sender: AnyObject) {

        var url: String = "https://www.youtube.com/watch?v=hS5CfP8n_js"
        let testURL = NSURL(string:url)
        if testURL != nil {
            extractor = LBYouTubeExtractor(URL: testURL, quality: LBYouTubeVideoQualityLarge)
            extractor.extractVideoURLWithCompletionBlock({(videoURL, error) in
                if error == nil {
                    println(videoURL)
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {

                        let data = NSData(contentsOfURL: videoURL)!
                        let pathToDocs = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
                        let fileName = "video_\(self.videoID).mp4"
                        let yourPath = pathToDocs.stringByAppendingPathComponent(fileName)
                        data.writeToFile(yourPath, atomically: true)
                        println("File \(fileName) successfully saved")
                    })
                } else {
                    println("Failed extracting video URL using block due to error:\(error)")
                }

            })
        }
    }
}

my project is crashing at this line:

let data = NSData(contentsOfURL: videoURL)!

But I can get videoURL in console:

http%3A%2F%2Fr3---sn-tv0cgv5qc5oq-nu8e.googlevideo.com%2Fvideoplayback%3Fsver%3D3%26id%3D852e427cff27fe3b%26dur%3D55.681 ... ty=small

I don't know what I am missing.

Here is my sample project.

Community
  • 1
  • 1
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
  • I've downloaded and ran your project: the URL is invalid. It is incomplete and contains dots. I thought the URL you were showing here was truncated by the SO editor but the *actual* URL you get with this lib is truncated in the middle exactly like in your quote here. – Eric Aya Jul 10 '15 at 10:49
  • any solution for that? – Dharmesh Kheni Jul 10 '15 at 10:50
  • I haven't seen any error in your code (I didn't think I would find some, honestly, but you never know, typos happen), so the error must come from the lib; therefore I have no solution for that problem. Or maybe YouTube changed their API (again) and the lib is out of date? (just a guess, no idea actually). – Eric Aya Jul 10 '15 at 10:52
  • Actually lib is 2 year old. – Dharmesh Kheni Jul 10 '15 at 10:53

0 Answers0