斯威夫特3:从照片/相机胶卷负载照片,而无需使用的UIImagePickerController
问题描述:
This question has been asked before但还没有为斯威夫特3.没有答案,我找的,我是卡在过去的3周相同的解决方案。斯威夫特3:从照片/相机胶卷负载照片,而无需使用的UIImagePickerController
我已经做了我的研究,并观看了有关从图片/相机胶卷加载图像无数的YouTube视频到使用的UIImagePickerController的应用程序,但我想要访问的照片,而无需用户操作。
我想从相机胶卷中读取一系列照片,并将它们放入照片幻灯片中以逐一显示。如何在没有UIImagePickerController的情况下访问这些照片?
答
可以使用Photos
框架来从CameraRoll /相册中的照片。
这里是斯威夫特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()
也可以管理授权。您可以阅读关于Photos框架的更多信息。
你有没有试着用照片框架,您可以访问从相机胶卷或任何专辑照片,而无需利用imagePicker的 –
https://developer.apple.com/library/content/samplecode/UsingPhotosFramework/Introduction/Intro.html 检查这个示例代码由苹果 –
很抱歉,如果我听起来noob,我已经下载它,并无法运行在我的xcode 8.3。我不知道在哪里下载xcode 9. – Spiral1ng