Swift 3:不使用UIImagePickerController从照片/相机胶卷中加载照片

8

这个问题之前被问过,但是没有Swift 3的答案。我正在寻找相同的解决方案,而我已经卡在这里三周了。

我做了我的研究,并观看了许多有关使用UIImagePickerController从照片/相机卷载入图像到应用程序的YouTube视频,但我想要在没有用户操作的情况下访问照片。

我想要从相机卷中读取一系列的照片,并将它们放在幻灯片中逐个展示。如何在没有UIImagePickerController的情况下访问这些照片?


你试过使用Photos框架吗?它可以让你在不使用imagePicker的情况下访问相机胶卷或任何相册中的照片。 - iOS Geek
请查看苹果公司提供的此示例代码:https://developer.apple.com/library/content/samplecode/UsingPhotosFramework/Introduction/Intro.html - iOS Geek
抱歉如果我听起来像个新手,我已经下载了它,但无法在我的Xcode 8.3上运行。而且我不知道从哪里下载Xcode 9。 - Spiral1ng
@Spiral1ng 请检查我的回答。Xcode 9目前处于测试版阶段。您可以继续使用Xcode 8.3进行操作。 - Rajan Maheshwari
1个回答

23

您可以使用Photos框架从CameraRoll / Photos获取照片。

这是< strong> Swift 3 代码的版本。

导入照片框架

import Photos

//Array of PHAsset type for storing photos
var images = [PHAsset]()

viewDidLoad或其他你想获取照片的地方使用此函数来获取照片。

func getImages() {
    let assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil)
    assets.enumerateObjects({ (object, count, stop) in
       // self.cameraAssets.add(object)
        self.images.append(object)
    })

    //In order to get latest image first, we just reverse the array
    self.images.reverse() 

    // To show photos, I have taken a UICollectionView       
    self.photosCollectionView.reloadData()
}

接下来是UICollectionView的数据源和代理方法。查看cellForItem数据源方法以了解如何显示图片。

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       return images.count
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCollectionViewCell", for: indexPath) as! PhotoCollectionViewCell
    let asset = images[indexPath.row]
    let manager = PHImageManager.default()
    if cell.tag != 0 {
            manager.cancelImageRequest(PHImageRequestID(cell.tag))
        }
    cell.tag = Int(manager.requestImage(for: asset,
                                            targetSize: CGSize(width: 120.0, height: 120.0),
                                            contentMode: .aspectFill,
                                            options: nil) { (result, _) in
                                                cell.photoImageView?.image = result
        })
    return cell
}

根据您的需要调整下面的代表。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = self.view.frame.width * 0.32
    let height = self.view.frame.height * 0.179910045
    return CGSize(width: width, height: height)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 2.5
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

请确保照片权限处于开启状态ON。如果您选择不允许,那么您需要使用PHPhotoLibrary.authorizationStatus()来管理授权。

您可以阅读有关照片框架的更多信息。


1
使用此函数在viewDidLoad或您想要获取照片的任何操作中获取照片。确保在后台线程上执行获取操作,然后在主线程上重新加载视图! - NRitH
@NRitH 没错。 - Rajan Maheshwari
非常感谢您的回复。代码编译时没有出现任何错误。但是我看到一个空白屏幕,应用程序中没有加载任何图像(已经出现了访问照片的权限提示)。我添加了一个名为photosCollectionView的UICollectionView。我是否应该在这个UICollectionView中看到照片?对于问题感到抱歉。 - Spiral1ng
只需允许权限,然后您将获得一组图像,可以在集合视图、表格视图或任何您想要的地方使用。 - Rajan Maheshwari
@Spiral1ng,这对你有帮助吗? - Rajan Maheshwari
enumerateObjects 方法的执行顺序是不确定的,因此依赖其顺序正确然后反转数组可能是不可靠的。您可能需要按照 PHPhoto 的 creationDate 属性进行排序。 - aronspring

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接