IOS-如何在图库中查找相似的照片-Swift

问题描述 投票:-1回答:1

我不知道如何获取所有照片,然后在照片库中找到相似的照片。请帮助我!

ios swift photo
1个回答
-1
投票

尝试一下,

第一张导入的照片

import Photos

然后在viewDidLoad()之前声明用于存储照片的数组

var allPhotos : PHFetchResult<PHAsset>? = nil

现在编写用于在viewDidLoad()中获取照片的代码

    /// Load Photos
PHPhotoLibrary.requestAuthorization { (status) in
    switch status {
    case .authorized:
        print("Good to proceed")
        let fetchOptions = PHFetchOptions()
        self.allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
    case .denied, .restricted:
        print("Not allowed")
    case .notDetermined:
        print("Not determined yet")
    }
}

现在编写此代码以显示来自阵列的图像

/// Display Photo
let asset = allPhotos?.object(at: indexPath.row)
self.imageview.fetchImage(asset: asset!, contentMode: .aspectFit, targetSize: self.imageview.frame.size) 


// Or Display image in Collection View cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "photoCell", for: indexPath) as! SelectPhotoCell

let asset = allPhotos?.object(at: indexPath.row)
cell.imgPicture.fetchImage(asset: asset!, contentMode: .aspectFit, targetSize: cell.imgPicture.frame.size)

return cell
}

extension UIImageView{
 func fetchImage(asset: PHAsset, contentMode: PHImageContentMode, targetSize: CGSize) {
let options = PHImageRequestOptions()
options.version = .original
PHImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: contentMode, options: options) { image, _ in
    guard let image = image else { return }
    switch contentMode {
    case .aspectFill:
        self.contentMode = .scaleAspectFill
    case .aspectFit:
        self.contentMode = .scaleAspectFit
    }
    self.image = image
    }
   }
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.