Search code examples
iosswiftscreenshotwhatsapp

UIDocumentInreactionController won't allow NSURL for .URL (Swift)


I'm basically taking a screenshot of a view, saving it to my camera roll , getting the NSURL path and exporting to Whatsapp

    //Create the UIImage
    UIGraphicsBeginImageContext(view.frame.size)
    view.layer.renderInContext(UIGraphicsGetCurrentContext())
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    //Save it to camera roll round 2
    var library = ALAssetsLibrary()

    library.writeImageToSavedPhotosAlbum(image.CGImage, metadata: nil, completionBlock: {
        (path:NSURL!, error:NSError!) -> Void in

        if NSThread.currentThread() == NSThread.mainThread(){
            println("\(path)")
            var controller = UIDocumentInteractionController()
            controller.delegate = self
            controller.UTI = "net.whatsapp.image"
            controller.URL = path
            controller.presentOpenInMenuFromRect(CGRectZero, inView: self.view, animated: true)

        }
    })

I'm getting this error :

Assertion failure in -[UIDocumentInteractionController setURL:], /SourceCache/UIKit/UIKit-3318.16.21/UIDocumentInteractionController.m:1024

But according to Apple's Documentation , it has to be a NSURL (https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDocumentInteractionController_class/#//apple_ref/occ/instp/UIDocumentInteractionController/URL)

Any ideas?


Solution

  • Once a image is saved in camera roll or somewhere outside of your application, you can access it using URL with 'assets-library scheme'.

    But UIDocumentInteractionController's URL property only supports URL with 'file scheme'.

    So you need to save your image to your application's temporary directory and set 'path' property to it's file scheme URL.