ios - 如何在不花时间使用 Swift 的情况下从 iPhone 获取所有包含图像的相册?

标签 ios iphone swift xcode

我试图从相册中获取所有图像。它获取所有图像及其 URL 和图像数据,但它不会直接从给定的 URL 路径获取图像,因此我需要在文档目录中下载图像,然后获取路径。所以这需要太多时间。我使用下面的代码。我想要获取图像,例如 iPhone 照片库获取。

请找出错误。

    func fatchImagesfromAlbum() {

        DispatchQueue.global(qos: .background).async {
        self.photoAssets = self.fetchResult as! PHFetchResult<AnyObject>

        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)


        self.photoAssets = PHAsset.fetchAssets(in: self.assetCollection, options: fetchOptions) as! PHFetchResult<AnyObject>

        for i in 0..<self.photoAssets.count{
            autoreleasepool {

                let asset = self.photoAssets.object(at: i)

                let imageSize = CGSize(width: asset.pixelWidth,
                                       height: asset.pixelHeight)

                let options = PHImageRequestOptions()
                options.deliveryMode = .fastFormat
                options.isSynchronous = true
                options.isNetworkAccessAllowed = true


                self.imageManager.requestImage(for: asset as! PHAsset, targetSize: imageSize, contentMode: .aspectFill, options: options, resultHandler: { (image, info) -> Void in

                    if image != nil {
                    let image1 = image as! UIImage
                    let imageUrl          = info!["PHImageFileURLKey"] as? NSURL
                    let imageName         = imageUrl?.lastPathComponent
                    let urlString: String = imageUrl!.path!
                    let theFileName = (urlString as NSString).lastPathComponent
                    self.imageName.append("\(theFileName)")
                    self.imagePath.append("\(urlString)")

                    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
                    let photoURL          = NSURL(fileURLWithPath: documentDirectory)
                    let localPath         = photoURL.appendingPathComponent(imageName!)
                    DispatchQueue.global(qos: .background).async {
                        if !FileManager.default.fileExists(atPath: localPath!.path) {
                            do {
                                try UIImageJPEGRepresentation(image1, 0.1)?.write(to: localPath!)
                                print("file saved")
                            }catch {
                                print("error saving file")
                            }
                        }
                        else {
                            print("file already exists")
                        }
                    }
                }
              })
                DispatchQueue.main.async
                    {
                        self.collectionView.reloadData()
                }
            }
        }
        self.hudHide()
    }
        PHPhotoLibrary.shared().register(self)

    if fetchResult == nil {
        let allPhotosOptions = PHFetchOptions()
        allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
        fetchResult = PHAsset.fetchAssets(with: allPhotosOptions)
    }
       }

最佳答案

我建议只使用 UIImagePickerController,或者如果您的应用需要多个图像选择功能,则建议使用第三方库,例如 DKImagePickerController。正如另一位用户在评论中提到的那样,这些只会将用户选择的图像复制到您的应用目录中,从而节省处理时间。

关于ios - 如何在不花时间使用 Swift 的情况下从 iPhone 获取所有包含图像的相册?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52554659/

相关文章:

ios - 使用 UISwitch 显示和隐藏 UITableViewCell 时崩溃太快

ios - Swift- 将数据从多节 TableView 传递到 ViewController

swift - UIBlurEffect View 不覆盖背景图片

ios - 缺少代码签名权利 - 在 bundle 'com.google.Googleplus' 中找不到任何权利

ios - Swift 项目比我预期的要大

ios - 为什么我的 JSON URL 不输出 JSON 数据?

iphone - URL 连接 : What is the difference between the following?

iphone - UIViewController 或 UINavigationController 是否设置其 View 的大小?

swift - 快速向左滑动手势时出现无法识别的选择器错误

ios - 按每个对象的 bool 值排序并显示在 Collection View 中