Essayez d'utiliser ceci. J'espère que c'est ce que vous cherchez.
import UIKit
import Photos
protocol CameraRollViewControllerProtocol: class {
func displayTappedImage(displayImage: UIImage)
func scrollToCameraButtonTapped()
}
class CameraRollViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet var collectionView: UICollectionView!
var images = [PHAsset]()
var displayImage: UIImage!
// used to specify the target size of the thumbnails of images in cameraRoll
// In iPhone6 images of target size 100.0 were successfully obtained and in iPhone 6plus images of 400.0 were obtained successfully; for other target size a nil image was obtained.
var thumbImageSize: Double!
var targetSize: CGSize!
weak var delegate: CameraRollViewControllerProtocol!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.contentInset = UIEdgeInsets(top: 24.0, left: 24.0, bottom: 24.0, right: 24.0)
// if UIScreen.main.bounds.width > 375 {
// thumbImageSize = 100.0
// } else {
thumbImageSize = 100.0
// }
}
override func viewWillAppear(_ animated: Bool) {
collectionView.isUserInteractionEnabled = true
self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.foregroundColor: UIColor.cameraRollNavigationBarTitle, NSAttributedStringKey.font: UIFont.gothamRoundedMedium20!]
checkPermission { (success) in
if success {
OperationQueue.main.addOperation({
self.getImages()
})
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidAppear(animated)
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "galleryPhotoCell", for: indexPath) as? CameraRollCell {
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: thumbImageSize, height: thumbImageSize),
contentMode: .aspectFill,
options: nil) { (result, _) in
if result != nil {
cell.imageView?.image = result
} else {
cell.imageView.image = #imageLiteral(resourceName: "cloud-Image")
}
})
return cell
}
else {
return UICollectionViewCell()
}
}
@IBAction func CameraButtonTapped(_ sender: Any) {
delegate.scrollToCameraButtonTapped()
}
}
extension CameraRollViewController {
func getImages() {
if images.count > 0 {
images.removeAll()
}
let assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil) //fetchOptions)//nil)
assets.enumerateObjects({ (object, count, stop) in
self.images.append(object)
})
self.images.reverse()
self.collectionView.reloadData()
}
func checkPermission( completionHandler:@escaping (_ success:Bool)->()) {
PHPhotoLibrary.requestAuthorization({ (status:PHAuthorizationStatus) in
if status == .authorized {
completionHandler(true)
} else {
completionHandler(false)
}
})
}
}
extension CameraRollViewController {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 96.0, height: 96.0)
}
func collectionView(_ collectionView: UICollectionView, layout
collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 20.0
}
}
extension CameraRollViewController {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// check size of Asset before loading it
let asset = images[indexPath.row]
let resources = PHAssetResource.assetResources(for: asset)
var sizeOnDisk: Int64? = 0
if let resource = resources.first {
let unsignedInt64 = resource.value(forKey: "fileSize") as? CLong
sizeOnDisk = Int64(bitPattern: UInt64(unsignedInt64!))
}
LogManager.logInfo("SIZE OF IMAGE: \(converByteToHumanReadable(sizeOnDisk!))")
let imageSizeString = sizeOnDisk!/1048576
LogManager.logInfo(" SIZE OF IMAGE (1048576): \(imageSizeString)")
if imageSizeString > 2 {
targetSize = CGSize.init(width: 1000.0, height: 1000.0)
} else {
targetSize = PHImageManagerMaximumSize
}
let manager = PHImageManager.default()
let options: PHImageRequestOptions = PHImageRequestOptions()
//options.resizeMode = .exact
options.deliveryMode = .highQualityFormat //.opportunistic
//options.resizeMode = .exact
manager.requestImage(for: asset,
targetSize: targetSize, //CGSize(width: 375.0, height: 667.0) ,
contentMode: .aspectFit,
options: options) { (result, info) in
if (info![PHImageResultIsInCloudKey] != nil) {
print("\n\nIS IN CLOUD: \(info![PHImageResultIsInCloudKey] as! Bool)")
}
guard info![PHImageResultIsDegradedKey] as! Bool == false else {
LogManager.logInfo("Image is degraded")
return
}
if let image = result {
print("\n\n*********************************==========Local Image*********************************==========\n\n")
let imageData: NSData = NSData(data: UIImageJPEGRepresentation((image), 1)!)
let frameImageData: NSData = NSData(data: UIImageJPEGRepresentation((image), 0.1)!)
let frameImageCompressed: UIImage = UIImage(data: frameImageData as Data)!
LogManager.logInfo(" SIZE OF IMAGE LOADED EARLIER : \(image.size); \(imageData.length/1048576).\(imageData.length%1048576)")
LogManager.logInfo("SIZE OF IMAGE LOADED NOW : \(frameImageCompressed.size); \(frameImageData.length/1048576).\(frameImageData.length%1048576)")
self.displayImage = image
self.delegate.displayTappedImage(displayImage: self.displayImage)
} else {
// if (self.getImage(asset: asset)) != nil {
// self.displayImage = self.getImage(asset: asset) //image
// self.delegate.displayTappedImage(displayImage: self.displayImage)
//UNCOMMENT LATER
print("\n\n*********************************==========Cloud Image*********************************==========\n\n")
let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.isSynchronous = true
//options.isNetworkAccessAllowed = true
options.progressHandler = { (progress, error, stop, info) in
print("PROGRESS: \(progress)") //.debug("\(progress)")
}
options.version = PHImageRequestOptionsVersion.original
PHImageManager.default().requestImage(for: asset, targetSize: UIScreen.main.bounds.size , contentMode: .aspectFill, options: options) { (image, info) in
if image != nil {
//print(info!["PHImageResultIsInCloudKey"] as! Bool)
//compressedImageData = self.compressImage(image: image!)
self.displayImage = image
self.delegate.displayTappedImage(displayImage: self.displayImage)
} else{
// request image with size 200x200
print("MUST NOT EXECUTE")
print("\n\n*********************************==========Local THUMBNAIL Image*********************************==========\n\n")
let options: PHImageRequestOptions = PHImageRequestOptions()
//options.resizeMode = .exact
options.deliveryMode = .highQualityFormat //.opportunistic
//options.resizeMode = .exact
PHImageManager.default().requestImage(for: asset, targetSize: CGSize.init(width: 150, height: 150), contentMode: .aspectFill, options: options) { (image, info) in
if image != nil {
self.displayImage = image
self.delegate.displayTappedImage(displayImage: self.displayImage)
}
}
}
}
//UNCOMMENT LATER
// }
// else {
// show popup saying download the image from icloud in this device as it's just a thumbnail
// self.createAlert(title: "Photo Not Accessible", message: "Please download it from iCloud to use it.")
// }
}
}
collectionView.isUserInteractionEnabled = false
}
}
extension CameraRollViewController {
func createAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
LogManager.logInfo("OK Pressed")
self.collectionView.isUserInteractionEnabled = true
}))
self.present(alert, animated: true, completion: nil)
}
func converByteToHumanReadable(_ bytes:Int64) -> String {
let formatter:ByteCountFormatter = ByteCountFormatter()
formatter.countStyle = .binary
return formatter.string(fromByteCount: Int64(bytes))
}
func getImage(asset: PHAsset) -> UIImage? {
var assetImage: UIImage?
let options = PHImageRequestOptions()
options.isSynchronous = true
options.isNetworkAccessAllowed = true
PHImageManager.default().requestImage(for: asset, targetSize: UIScreen.main.bounds.size, contentMode: .aspectFill, options: options) { (image, info) in
assetImage = image
}
return assetImage
}
}
0 votes
Avez-vous réussi à trouver un problème ?
0 votes
Ce bogue apparaît également lorsque je sauvegarde la photo sans l'insérer dans la collection. Comme ceci : var placeholderAssetBlock : PHObjectPlaceholder ? PHPhotoLibrary.shared().performChanges({ let asset = PHAssetChangeRequest.creationRequestForAsset(from : photo) placeholderAssetBlock = asset.placeholderForCreatedAsset }
0 votes
Quelle est l'exception qui est levée ?
0 votes
@combinatorial *** Terminer l'application en raison d'une exception non attrapée 'NSGenericException', reason : 'The operation couldn't be completed. (Erreur Cocoa -1.)'
0 votes
@combinatorial here crash log typical pastebin.com/pEXQ5Bsn
0 votes
Avez-vous demandé une autorisation ?
0 votes
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
0 votes
@combinatorial sûr. Les gens sauvegardent des photos plusieurs fois et au hasard des tentatives, ils ont une panne.
0 votes
Laissez-nous continuer cette discussion dans le chat .
0 votes
Pourriez-vous partager le code pour
getMyImage
?0 votes
Je rencontre également ce problème dans iOS 10.2.1, utilisez-vous un iphone7 pour tester ?
1 votes
@Jam non, je n'ai pas testé sur 7. Je ne peux pas attraper cette erreur avec les tests. Je ne la vois que dans les rapports de crash d'autres utilisateurs.
0 votes
@JonRose c'est un code compliqué ;) Je fais une capture d'écran à partir de UIView, mais je pense que cela n'a pas d'importance de savoir comment je peux faire ou recevoir UIImage.
0 votes
J'ai ce problème sur un iPhone 6. Il est intéressant de noter qu'un co-testeur ne le voit pas sur un iPhone 7. Je n'ai aucune idée de la façon d'interpréter ce problème pour le moment.
0 votes
Pourrait
image
oalbum
être nulle ?0 votes
Cela se produit-il aussi dans ios 9 ?
0 votes
Jon Rose - non Saheb Roy - non
0 votes
Nous le voyons aussi. J'ai soumis un radar @ rdar://33197332. Avez-vous réussi à contourner ce problème ?
0 votes
Je fais face à ce problème aussi, à travers mon Crashlytics il s'est produit sur iOS 10 seulement, toutes les versions d'iOS 10
0 votes
Hé ! Des nouvelles ?