Swift Share extension, ALAsset is nil

618 Views Asked by At

i want to get some extra info about the images i'll share with the Share extension. I can create the UIImage from the url but when i want to obtain an ALAsset i get nil. Anyone had this problem?

itemProvider!.loadItemForTypeIdentifier(String(kUTTypeImage), options: nil, completionHandler: { (decoder: NSSecureCoding!, error: NSError!) -> Void in
if ALAssetsLibrary.authorizationStatus() == ALAuthorizationStatus.Authorized {

                    if let url = decoder as? NSURL {
                        ALAssetsLibrary().assetForURL(url, resultBlock: { (myasset:ALAsset!) -> Void in

                            println(url)
                            println(fm.fileExistsAtPath(url.path!))
                            println(myasset)
                            let location = myasset?.valueForProperty(ALAssetPropertyLocation) as CLLocation?
                            let date = myasset?.valueForProperty(ALAssetPropertyDate) as NSDate?
                            self.extensionContext?.completeRequestReturningItems([AnyObject](), completionHandler: nil)

                        }, failureBlock: { (myerror:NSError!) -> Void in


                        })
                    }
                }

The output is

file:///var/mobile/Media/DCIM/102APPLE/IMG_2977.JPG
true
nil
1

There are 1 best solutions below

2
On

the immediate issue is you are passing a file url in place of an asset url for this line: ALAssetsLibrary().assetForURL(url, resultBlock: { (myasset:ALAsset!) -> Void in. Share extensions return the url to the path on the iphone's file system...something of the form: file:///..... These are not the same as the urls that an ALAsset require in the assetForURL method.

Unfortunately, though this makes the code more correct, it still doesn't fix the issue. I spent some time with many different approaches. Writing a new image to disk via the AssetsLibrary and the given file path will return an asset url upon completion which will work successfully - though you obviously don't want duplicate photos in your camera roll. (Note: there is no way to delete an ALAsset). You could probably hold onto the file path and delete the new image when you are done with it, but that is an extremely messy approach.

I ended up rewriting my approach given these limitations.