我有照片库图像的集合视图但是第一次用户允许使用照片时出现问题 - 当应用程序第一次运行且用户允许使用照片时,用户无法看到任何图像关闭视图控制器并再次返回查看图像
这是代码:
import UIKit
import Photos
class typeandtranslateViewController: UIViewController , UIImagePickerControllerDelegate , UINavigationControllerDelegate , UICollectionViewDelegate, UICollectionViewDataSource , UITextFieldDelegate {
static var checkTextField = Bool()
@IBOutlet var backgroundimg: UIImageView!
@IBOutlet var frontimg: UIImageView!
@IBOutlet weak var typeView: UIView!
let arr_img = NSMutableArray()
let arr_selected = NSMutableArray()
@IBOutlet var collview: UICollectionView!
@IBOutlet weak var sefareshTitleTextField: UITextField!
@IBAction func caneraButton(_ sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera ;
imagePicker.allowsEditing = false
self.present(imagePicker,animated: true , completion: nil)
}
print("Camera!")
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
UIImageWriteToSavedPhotosAlbum(selectedImage,self,nil,nil)
dismiss(animated: true, completion: nil)
print("save Image ")
}
@IBOutlet weak var viewCamera: UIView!
override func viewDidLoad() {
super.viewDidLoad()
print("Text Field Condition ")
if sefareshTitleTextField!.text! == "" {
typeandtranslateViewController.checkTextField = false
print("sefaresh title is nill")
} else if sefareshTitleTextField!.text! != "" {
typeandtranslateViewController.checkTextField = true
print("sefaresh title isnt nill")
}
self.sefareshTitleTextField.delegate = self
collview?.allowsMultipleSelection = true
let allPhotosOptions : PHFetchOptions = PHFetchOptions.init()
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let allPhotosResult = PHAsset.fetchAssets(with: .image, options: allPhotosOptions)
allPhotosResult.enumerateObjects({ (asset, idx, stop) in
self.arr_img.add(asset)
})
self.typeView.layer.cornerRadius = self.typeView.frame.size.height/50
self.typeView.layer.borderWidth = 1
self.typeView.layer.borderColor = UIColor.clear.cgColor
self.typeView.clipsToBounds = true
self.viewCamera.layer.cornerRadius = 5
self.viewCamera.layer.borderWidth = 1
self.viewCamera.layer.borderColor = UIColor.clear.cgColor
self.viewCamera.clipsToBounds = true
self.tabBarController?.tabBar.isHidden = true
self.navigationController?.isNavigationBarHidden = true
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = CGRect(x: self.backgroundimg.frame.origin.x, y: self.backgroundimg.frame.origin.y, width: self.backgroundimg.frame.size.width, height: self.backgroundimg.frame.size.height)
blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.backgroundimg.addSubview(blurView)
}
func getAssetThumbnail(asset: PHAsset, size: CGFloat) -> UIImage {
let retinaScale = UIScreen.main.scale
let retinaSquare = CGSize(width: size * retinaScale, height: size * retinaScale)//CGSizeMake(size * retinaScale, size * retinaScale)
let cropSizeLength = min(asset.pixelWidth, asset.pixelHeight)
let square = CGRect(x: 0, y: 0, width: cropSizeLength, height: cropSizeLength)//CGRectMake(0, 0, CGFloat(cropSizeLength), CGFloat(cropSizeLength))
let cropRect = square.applying(CGAffineTransform(scaleX: 1.0/CGFloat(asset.pixelWidth), y: 1.0/CGFloat(asset.pixelHeight)))
let manager = PHImageManager.default()
let options = PHImageRequestOptions()
var thumbnail = UIImage()
options.isSynchronous = true
options.deliveryMode = .highQualityFormat
options.resizeMode = .exact
options.normalizedCropRect = cropRect
manager.requestImage(for: asset, targetSize: retinaSquare, contentMode: .aspectFit, options: options, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true);
if sefareshTitleTextField!.text == "" {
typeandtranslateViewController.checkTextField = false
print("sefaresh title is nill")
} else if sefareshTitleTextField!.text! != "" {
typeandtranslateViewController.checkTextField = true
print("sefaresh title isnt nill")
}
return false;
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if sefareshTitleTextField!.text! == "" {
typeandtranslateViewController.checkTextField = false
print("sefaresh title is nill")
} else if sefareshTitleTextField!.text! != "" {
typeandtranslateViewController.checkTextField = true
print("sefaresh title isnt nill")
}
}
//MARK:
//MARK: Collectioview methods
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return arr_img.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "celll",
for: indexPath)
let imgview : UIImageView = cell.viewWithTag(20) as! UIImageView
imgview.image = self.getAssetThumbnail(asset: self.arr_img.object(at: indexPath.row) as! PHAsset, size: 150)
let selectView : UIImageView = cell.viewWithTag(22) as! UIImageView
if arr_selected.contains(indexPath.row){
selectView.image = UIImage(named: "Select.png")
}else{
selectView.image = UIImage(named: "radioCircleButton.png")
}
cell.layer.cornerRadius = 5
cell.layer.borderWidth = 1
cell.layer.borderColor = UIColor.clear.cgColor
cell.clipsToBounds = true
return cell
}
var selectedIndexes = [NSIndexPath]() {
didSet {
collview.reloadData()
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
if arr_selected.contains(indexPath.row){
arr_selected.remove(indexPath.row)
}else{
arr_selected.add(indexPath.row)
}
self.collview.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = backgroundimg.bounds
backgroundimg.addSubview(blurView)
backgroundimg.frame = self.view.bounds
}
@IBAction func backToTheMainCustom(_ sender: UIButton) {
performSegue(withIdentifier: "backToTheMainCustom", sender: self)
sefareshTitleTextField!.text! = ""
typeandtranslateViewController.checkTextField = false
}
}
答案 0 :(得分:1)
首先,您需要询问用户是否有权访问照片库。如果请求第一次发生,请等待他的回答并再次打开UIImagePickerController。请查看以下代码:
let photosAccess = PHPhotoLibrary.authorizationStatus()
switch photosAccess {
case .notDetermined:
// First time here. Request the access
PHPhotoLibrary.requestAuthorization({status in
if status == .authorized{
// Access was just granted
// Open library here
}
})
case .authorized:
// Open library here
case .denied, .restricted:
// Photos access is not granted.
// Good place to take user to app settings.
}
相机相同:
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { response in
if response {
DispatchQueue.main.async {
// Show camera UI here
}
} else {
DispatchQueue.main.async {
// Access is restricred
}
}
}