返回 导航

Swift

hangge.com

Swift - 使用ALAssetsLibrary获取相簿里所有图片,视频(附样例)

作者:hangge | 2015-06-14 13:24
1,ALAssetsLibrary介绍
(1)通过创建ALAssetsLibrary的实例可以访问系统Photos里的图片与视频。这里图片不仅包括相机拍摄的照片,还包括从iTunes导入的和从其他设备里面导入的图片。
(2)从ALAssetsLibrary实例中获取得到的对象的生命周期和ALAssetsLibrary这个实例的生命周期一致。
(3)通过enumerateGroupsWithTypes方法可以遍历所有的照片分组,再用分组的enumerateAssetsUsingBlock方法可以遍历该分组下所有的照片。
(4)通过valueForProperty获取到图片的信息,包括类型, Location , 时长,方向,日期,格式 , URL地址

2,下面做一个查看相册图片的APP
(1)程序启动后会加载相机胶卷里所有的照片,并以缩略图的形式展示出来
(2)点击缩略图,可以查看照片的原图以及图片的相关信息

3,效果图如下:
    

4,详细代码
--- 首页 ViewController.swift ---
import UIKit
import AssetsLibrary

class ViewController: UICollectionViewController {
    //资源库管理类
    var assetsLibrary =  ALAssetsLibrary()
    //保存照片集合
    var assets = [ALAsset]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        var countOne = 0
        //ALAssetsGroupSavedPhotos表示只读取相机胶卷(ALAssetsGroupAll则读取全部相簿)
        assetsLibrary.enumerateGroupsWithTypes(ALAssetsGroupSavedPhotos, usingBlock: {
            (group: ALAssetsGroup!, stop) in
            print("is goin")
            if group != nil
            {
                let assetBlock : ALAssetsGroupEnumerationResultsBlock = {
                    (result: ALAsset!, index: Int, stop) in
                    if result != nil
                    {
                        self.assets.append(result)
                        countOne++
                    }
                }
                group.enumerateAssetsUsingBlock(assetBlock)
                print("assets:\(countOne)")
                //collectionView网格重载数据
                self.collectionView?.reloadData()
            }
            }, failureBlock: { (fail) in
                print(fail)
        })
    }
    
    
    // CollectionView行数
    override func collectionView(collectionView: UICollectionView,
        numberOfItemsInSection section: Int) -> Int {
            return assets.count;
    }
    
    // 获取单元格
    override func collectionView(collectionView: UICollectionView,
        cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
            // storyboard里设计的单元格
            let identify:String = "DesignViewCell"
            // 获取设计的单元格,不需要再动态添加界面元素
            let cell = (self.collectionView?.dequeueReusableCellWithReuseIdentifier(
                identify, forIndexPath: indexPath))! as UICollectionViewCell
            
            //取缩略图
            let myAsset = assets[indexPath.item]
            let image = UIImage(CGImage:myAsset.thumbnail().takeUnretainedValue())
            // 从界面查找到控件元素并设置属性
            (cell.contentView.viewWithTag(1) as! UIImageView).image = image
            return cell
    }
    
    // 单元格点击响应
    override func collectionView(collectionView: UICollectionView,
        didSelectItemAtIndexPath indexPath: NSIndexPath) {
            var myAsset = assets[indexPath.item]
            
            //这里不使用segue跳转(建议用segue跳转)
            let detailViewController = UIStoryboard(name: "Main", bundle: nil)
                .instantiateViewControllerWithIdentifier("detail")
                as! ImageDetailViewController
            detailViewController.myAsset = self.assets[indexPath.row]
            
            // navigationController跳转到detailViewController
            self.navigationController!.pushViewController(detailViewController,
                animated:true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

--- 详情页 ImageDetailViewController.swift ---
import UIKit
import AssetsLibrary

class ImageDetailViewController: UIViewController {
    //选中的图片资源
    var myAsset:ALAsset!
    //用于显示图片信息
    @IBOutlet weak var textView: UITextView!
    //用于显示原图
    @IBOutlet weak var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //获取文件名
        let representation =  myAsset.defaultRepresentation()
        self.title = representation.filename()
        
        //获取图片信息
        textView.text = "日期:\(myAsset.valueForProperty(ALAssetPropertyDate))\n"
            + "类型:\(myAsset.valueForProperty(ALAssetPropertyType))\n"
            + "位置:\(myAsset.valueForProperty(ALAssetPropertyLocation))\n"
            + "时长:\(myAsset.valueForProperty(ALAssetPropertyDuration))\n"
            + "方向:\(myAsset.valueForProperty(ALAssetPropertyOrientation))"
        
        //获取原图
        let imageBuffer = UnsafeMutablePointer<UInt8>.alloc(Int(representation.size()))
        let bufferSize = representation.getBytes(imageBuffer, fromOffset: Int64(0),
            length: Int(representation.size()), error: nil)
        let data =  NSData(bytesNoCopy:imageBuffer ,length:bufferSize, freeWhenDone:true)
        imageView.image = UIImage(data: data)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

5,源码下载:hangge_763.zip
评论

全部评论(2)

回到顶部