Я много пробовал, но не могу решить. Ниже приведен код, который я пробовал. Получение вопроса на
cell.userImageView.image = self.selectedPhotos[0] // Thread 1: EXC_BAD_ACCESS (code=2, address=0x1208e5520)
Строка выше находится внутри
func convertAssetsToImage(cell: UserProfilePhotosCell)
Я использую BSImagePicker, чтобы выбрать изображения из галереи. Вот полный код:
import UIKit
import BSImagePicker
import Photos
class UserProfileVC: BaseCollectionViewController {
// MARK: Properties
let userPhotoId = "userPhotoId"
var SelectedAssets = [PHAsset]()
var selectedPhotos = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = .white
collectionView.register(UserProfilePhotosCell.self, forCellWithReuseIdentifier: userPhotoId)
print("Did load once")
}
@objc func showCustomImagePicker(cell1: UserProfilePhotosCell) {
let imagePicker = ImagePickerController()
imagePicker.settings.selection.max = 1
imagePicker.settings.selection.unselectOnReachingMax = true
imagePicker.settings.fetch.assets.supportedMediaTypes = [.image]
imagePicker.albumButton.tintColor = UIColor.green
imagePicker.cancelButton.tintColor = UIColor.red
imagePicker.doneButton.tintColor = UIColor.purple
imagePicker.navigationBar.barTintColor = .black
imagePicker.settings.theme.backgroundColor = .black
imagePicker.settings.theme.selectionFillColor = UIColor.gray
imagePicker.settings.theme.selectionStrokeColor = UIColor.yellow
imagePicker.settings.theme.selectionShadowColor = UIColor.red
imagePicker.settings.theme.previewTitleAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16),NSAttributedString.Key.foregroundColor: UIColor.white]
imagePicker.settings.theme.previewSubtitleAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12),NSAttributedString.Key.foregroundColor: UIColor.white]
imagePicker.settings.theme.albumTitleAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18),NSAttributedString.Key.foregroundColor: UIColor.white]
imagePicker.settings.list.cellsPerRow = {(verticalSize: UIUserInterfaceSizeClass, horizontalSize: UIUserInterfaceSizeClass) -> Int in
switch (verticalSize, horizontalSize) {
case (.compact, .regular): // iPhone5-6 portrait
return 2
case (.compact, .compact): // iPhone5-6 landscape
return 2
case (.regular, .regular): // iPad portrait/landscape
return 3
default:
return 2
}
}
self.presentImagePicker(imagePicker, select: { (asset) in
print("Selected: \(asset)")
}, deselect: { (asset) in
print("Deselected: \(asset)")
}, cancel: { (assets) in
print("Canceled with selections: \(assets)")
}, finish: { (assets) in
print("Finished with selections: \(assets)")
print("Count of Assets: \(assets.count)")
self.SelectedAssets = assets
self.convertAssetsToImage(cell: cell1)
})
}
func convertAssetsToImage(cell: UserProfilePhotosCell) {
for asset in SelectedAssets {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
manager.requestImage(for: asset, targetSize: CGSize(width: 340, height: 365), contentMode: .aspectFit, options: option, resultHandler: {(result, info) -> Void in
thumbnail = result!
})
self.selectedPhotos.append(thumbnail)
}
DispatchQueue.main.async {
cell.userImageView.image = self.selectedPhotos[0]
print("Dispatch")
}
}
}
extension UserProfileVC: UICollectionViewDelegateFlowLayout {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: userPhotoId, for: indexPath) as! UserProfilePhotosCell
cell.backgroundColor = .yellow
cell.userImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showCustomImagePicker(cell1:))))
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return .init(width: view.frame.width, height: 500)
}
}
Код пользовательской ячейки:
import UIKit
import BSImagePicker
import Photos
class UserProfilePhotosCell: UICollectionViewCell {
var userImageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "megan")
iv.contentMode = .scaleAspectFill
iv.layer.cornerRadius = 8
iv.clipsToBounds = true
iv.constrainHeight(constant: 200)
iv.backgroundColor = .red
iv.isUserInteractionEnabled = true
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
setupUI()
print("Did init once")
}
fileprivate func setupUI() {
addSubview(userImageView)
userImageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
// userImageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
userImageView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
userImageView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Я также попытался передать массив с изображениями в UserProfilePhotosCell и обновить userImageView.image внутри метода didSet, нет удачи, та же ошибка.
Заранее благодарю за любую помощь.