How to get the URL of an image just added in PHPhotoLibrary

后端 未结 6 886
臣服心动
臣服心动 2020-12-30 03:11

I am using the UIImagePickerController in two cases

  • to select an existing image in the Photo Library
  • to take a new picture

In the first

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 03:50

    I don't like this fix, as this could result in a race condition. So far I can't think of a better solution. If someone does I'd love to hear it :) Either way, here is a Swift-version of Rigel Chen's answer

    import Photos
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
    
            var localId:String?
            let imageManager = PHPhotoLibrary.sharedPhotoLibrary()
    
            imageManager.performChanges({ () -> Void in
    
                let request = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
                localId = request.placeholderForCreatedAsset?.localIdentifier
    
                }, completionHandler: { (success, error) -> Void in
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
    
                        if let localId = localId {
    
                            let result = PHAsset.fetchAssetsWithLocalIdentifiers([localId], options: nil)
                            let assets = result.objectsAtIndexes(NSIndexSet(indexesInRange: NSRange(location: 0, length: result.count))) as? [PHAsset] ?? []
    
                            if let asset = assets.first {
                                // Do something with result
                            }
                        }
                    })
            })
        }
    }
    

提交回复
热议问题