How to retrieve PHAsset from UIImagePickerController

前端 未结 4 1044
予麋鹿
予麋鹿 2021-02-07 12:42

I\'m trying to retrieve a PHAsset however PHAsset.fetchAssets(withALAssetURLs:options:) is deprecated from iOS 8 so how can I properly retrieve a PHAsset?

4条回答
  •  悲哀的现实
    2021-02-07 13:17

    I am not sure what you want.

    Are you trying to target iOS 8?

    This is how I fetch photos and it works in iOS (8.0 and later), macOS (10.11 and later), tvOS (10.0 and later). Code is commented where it may be confusing

    1. The first functions sets the options to fetch the photos
    2. The second function will actually fetch them

       //import the Photos framework
       import Photos
       //in these arrays I store my images and assets
       var images = [UIImage]()
       var assets = [PHAsset]()
      
       fileprivate func setPhotoOptions() -> PHFetchOptions{
              let fetchOptions = PHFetchOptions()
              fetchOptions.fetchLimit = 15
              let sortDescriptor = NSSortDescriptor(key: "creationDate", ascending: false)
              fetchOptions.sortDescriptors = [sortDescriptor]
              return fetchOptions
          }
      
      
      
      
      fileprivate func fetchPhotos() {
      let allPhotos = PHAsset.fetchAssets(with: .image, options: setPhotoOptions())
      
      DispatchQueue.global(qos: .background).async {
      
          allPhotos.enumerateObjects({ (asset, count, stop) in
              let imageManager = PHImageManager.default()
              let targetSize = CGSize(width: 200, height: 200)
              let options = PHImageRequestOptions()
              options.isSynchronous = true
              imageManager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit, options: options, resultHandler: { (image, info) in
      
                  if let image = image {
                      self.images.append(image)
                      self.assets.append(asset)
      
      
                  }
      
                  if count == allPhotos.count - 1 {
                      DispatchQueue.main.async {
                          //basically, here you can do what you want
                          //(after you finish retrieving your assets)
                          //I am reloading my collection view
                          self.collectionView?.reloadData()
                      }
                  }
      
              })
      
      
          })
      
      }
      

      }

    Edit based on OP's clarification

    You need to set the delegate UIImagePickerControllerDelegate

    then implement the following function

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    

    within said method, get the image like this:

    var image : UIImage = info[UIImagePickerControllerEditedImage] as! UIImage
    

提交回复
热议问题