讀取相冊(cè)內(nèi)的圖片和視頻-Swift

由于只是簡(jiǎn)單的描述如何獲取系統(tǒng)相冊(cè)內(nèi)的照片和視頻,這里就不貼我那很丑的的布局的Demo了

步驟

1.plist文件添加訪問(wèn)權(quán)限

2.導(dǎo)入需要支持的庫(kù) import Photos

import Photos

3.獲取所有內(nèi)容,官方API里面有很多獲取到 PHFetchResult<PHAsset>,可自行獲取

    lazy var photosArray : PHFetchResult<PHAsset> = {
        let allOptions = PHFetchOptions()
        // 按照時(shí)間排序
        /// 這里設(shè)置的key = 'creationDate' 排序字段可以按照已有的屬性去查 ascending:升序和降序?qū)傩?        /*
         open class func fetchAssets(in assetCollection: PHAssetCollection, options: PHFetchOptions?) -> PHFetchResult<PHAsset>
         
         open class func fetchAssets(withLocalIdentifiers identifiers: [String], options: PHFetchOptions?) -> PHFetchResult<PHAsset> // includes hidden assets by default
         
         open class func fetchKeyAssets(in assetCollection: PHAssetCollection, options: PHFetchOptions?) -> PHFetchResult<PHAsset>?
         
         open class func fetchAssets(withBurstIdentifier burstIdentifier: String, options: PHFetchOptions?) -> PHFetchResult<PHAsset>
         
         
         // Fetches PHAssetSourceTypeUserLibrary assets by default (use includeAssetSourceTypes option to override)
         open class func fetchAssets(with options: PHFetchOptions?) -> PHFetchResult<PHAsset>
         
         open class func fetchAssets(with mediaType: PHAssetMediaType, options: PHFetchOptions?) -> PHFetchResult<PHAsset>
         
         
         // assetURLs are URLs retrieved from ALAsset's ALAssetPropertyAssetURL
         @available(iOS, introduced: 8.0, deprecated: 11.0, message: "Will be removed in a future release")
         open class func fetchAssets(withALAssetURLs assetURLs: [URL], options: PHFetchOptions?) -> PHFetchResult<PHAsset>
         */
        allOptions.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: true)]
        let allResults = PHAsset.fetchAssets(with: allOptions)
        
        return allResults
    }()

效果圖:這里使用的是兩個(gè)UICollectionView .


1565575061776.jpg
  1. 獲取某一個(gè)相冊(cè)內(nèi)的個(gè)體: let asset: PHAsset? = photosArray[indexPath.row]

5.以下貼官方API的關(guān)于PHAsset部分屬性的代碼

    // Playback style describes how the asset should be presented to the user (regardless of the backing media for that asset).  Use this value to choose the type of view and the appropriate APIs on the PHImageManager to display this asset
    @available(iOS 11.0, *)
    open var playbackStyle: PHAsset.PlaybackStyle { get }

    /// 判斷獲取的是圖片,視頻,錄音,還是不知道...屬性
    /*
    public enum PHAssetMediaType : Int {

    
        case unknown

        case image

        case video

        case audio
    }
    */
    open var mediaType: PHAssetMediaType { get }

    open var mediaSubtypes: PHAssetMediaSubtype { get }

    
    open var pixelWidth: Int { get }

    open var pixelHeight: Int { get }

    
    open var creationDate: Date? { get }

    open var modificationDate: Date? { get }

    
    open var location: CLLocation? { get }

    
    open var duration: TimeInterval { get }

    
    // a hidden asset will be excluded from moment collections, but may still be included in other smart or regular album collections
    open var isHidden: Bool { get }

    
    open var isFavorite: Bool { get }

    
    open var burstIdentifier: String? { get }

    open var burstSelectionTypes: PHAssetBurstSelectionType { get }

    open var representsBurst: Bool { get }

6.判斷asset.mediaType的屬性.

7.根據(jù)mediaType來(lái)根據(jù)類方法獲取想要的內(nèi)容,類方法有很多,自行根據(jù)需求獲取

如下:

        if asset!.mediaType == .image{
            let size = CGSize(width: asset!.pixelWidth, height: asset!.pixelHeight)
            PHCachingImageManager.default().requestImage(for: asset!, targetSize: size, contentMode: .aspectFill, options: .none) { (img, dic) in
                self.imageView.image = img
            }
        }
        else if asset!.mediaType == .video {
                        let option = PHVideoRequestOptions()
            option.version = .current
            option.deliveryMode = .automatic
            option.isNetworkAccessAllowed = true
            
            PHCachingImageManager.default().requestAVAsset(forVideo: asset!, options: option) { (avsset, mix, dict) in
                if avsset != nil {
//                    guard let uslAsset: AVURLAsset = avsset as? AVURLAsset else {return}
                    
                    let generator = AVAssetImageGenerator.init(asset: avsset!)
                    generator.appliesPreferredTrackTransform = true
                    let time = CMTimeMakeWithSeconds(0.0,preferredTimescale: 600)
                    var actualTime:CMTime = CMTimeMake(value: 0,timescale: 0)
                    let imageRef:CGImage = try! generator.copyCGImage(at: time, actualTime: &actualTime)
                    
                    DispatchQueue.main.async {
                        self.imageView.image = UIImage.init(cgImage: imageRef)
                        let getSeconds = NSInteger(round(CMTimeGetSeconds(avsset!.duration)))
                        let seconds = getSeconds%60
                        let minutes = getSeconds%3600/60
                        let hours = getSeconds/3600
                    }
                }
            }
        }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 在微博上出現(xiàn)了越來(lái)越多的被標(biāo)記為 Live 的圖片,這種圖片是一種動(dòng)圖 LivePhoto,長(zhǎng)按之后會(huì)進(jìn)行播放。那...
    wvqusrtg閱讀 5,089評(píng)論 0 9
  • 相冊(cè)適配 前言 由于在iOS8及以后蘋果將原有的操作相冊(cè)的ALAssetsLibrary framework替換為...
    wentianen閱讀 1,936評(píng)論 0 6
  • 在微博上出現(xiàn)了越來(lái)越多的被標(biāo)記為 Live 的圖片,這種圖片是一種動(dòng)圖 LivePhoto,長(zhǎng)按之后會(huì)進(jìn)行播放。那...
    代碼移動(dòng)工程師閱讀 1,886評(píng)論 0 1
  • 寫在前面 在手機(jī)APP日益增加的前提下,如何更好的提升用戶的交互體驗(yàn)似乎成為衡量一個(gè)APP重要指標(biāo)。上述的感悟源于...
    Jack_lin閱讀 6,407評(píng)論 12 62
  • 周日 日常找餐廳吃飯。這家北京西路南匯路的店很贊~ 海鮮很多 小鮑魚~東星斑~賴尿蝦~等等等等。 最愛(ài)的還是煲仔飯...
    梅錫卿閱讀 609評(píng)論 0 1

友情鏈接更多精彩內(nèi)容