2017-05-22 134 views
4

我是Swift中的新成員。在下面的代碼中,它檢索照片並將它們放入數組中。現在我想用圖像查看它們。我該怎麼做?將圖像從PHAsset加載到Imageview中

我的意思是,如何在imageview中顯示數組的一個元素。

var list :[PHAsset] = [] 
PHPhotoLibrary.requestAuthorization { (status) in 
    switch status 
    { 
    case .authorized: 
     print("Good to proceed") 
     let fetchOptions = PHFetchOptions() 
     let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions) 
     print(allPhotos.count) 
     allPhotos.enumerateObjects({ (object, count, stop) in 
      list.append(object) 
     }) 

     print("Found \(allPhotos.count) images") 
    case .denied, .restricted: 
     print("Not allowed") 
    case .notDetermined: 
     print("Not determined yet") 
    } 

另一個問題是:當我調用這個函數看起來它異步執行。我的意思是調用該函數後的代碼行會提前執行。這是因爲requestAuthorization?

回答

1

你可以這樣做: -

創建類型PHAsset的空數組: -

fileprivate var imageAssets = [PHAsset]() 

通過調用這個函數提取所有圖像: -

func fetchGallaryResources(){ 
     let status = PHPhotoLibrary.authorizationStatus() 
     if (status == .denied || status == .restricted) { 
      self.showAlert(cancelTitle: nil, buttonTitles:["OK"], title: "Oops", message:"Access to PHPhoto library is denied.") 
      return 
     }else{ 
     PHPhotoLibrary.requestAuthorization { (authStatus) in 
      if authStatus == .authorized{ 
       let imageAsset = PHAsset.fetchAssets(with: .image, options: nil) 
       for index in 0..<imageAsset.count{ 
        self.imageAssets.append((imageAsset[index])) 
       } 
     } 

    } 

申請image像這樣: -

let availableWidth = UIScreen.main.bounds.size.width 
let availableHeight = UIScreen.main.bounds.size.height 

取出從imageAssets圖像中的循環或單一個就是這樣: -

PHImageManager.default().requestImage(for: imageAssets[0], targetSize: CGSize(width : availableWidth, height : calculatedCellWidth), contentMode: .default, options: nil, resultHandler: { (image, info) in 
     requestedImageView.image = image 

    }) 
+0

當我調用這個函數並且想要在imageview中設置圖像時,它會引發:致命錯誤:索引超出範圍。它的異步執行仍然存在。 –

+0

您的設備中是否有任何圖像? – Himanshu

+0

是的。我通過將最後一行代碼放入授權的閉包來解決它,並且它可以工作。但我想以同步的方式做到這一點。 –

4

試試這個:imageView.image = convertImageFromAsset(list[0])

func convertImageFromAsset(asset: PHAsset) -> UIImage { 
    let manager = PHImageManager.default() 
    let option = PHImageRequestOptions() 
    var image = UIImage() 
    option.isSynchronous = true 
    manager.requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in 
     image = result! 
    }) 
    return image 
} 

希望它能幫助。

+0

好奇,爲什麼這被否決,因爲它是正確的代碼 – Spads

+1

謝謝。它回答我的第一個問題。 –

相關問題