这个问题之前被问过,但是没有Swift 3的答案。我正在寻找相同的解决方案,而我已经卡在这里三周了。
我做了我的研究,并观看了许多有关使用UIImagePickerController从照片/相机卷载入图像到应用程序的YouTube视频,但我想要在没有用户操作的情况下访问照片。
我想要从相机卷中读取一系列的照片,并将它们放在幻灯片中逐个展示。如何在没有UIImagePickerController的情况下访问这些照片?
这个问题之前被问过,但是没有Swift 3的答案。我正在寻找相同的解决方案,而我已经卡在这里三周了。
我做了我的研究,并观看了许多有关使用UIImagePickerController从照片/相机卷载入图像到应用程序的YouTube视频,但我想要在没有用户操作的情况下访问照片。
我想要从相机卷中读取一系列的照片,并将它们放在幻灯片中逐个展示。如何在没有UIImagePickerController的情况下访问这些照片?
您可以使用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()
来管理授权。
您可以阅读有关照片框架的更多信息。