码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-09-28 11:13:18      阅读:861      评论:0      收藏:0      [点我收藏+]

标签:

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

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

3,效果图如下:
  技术分享  技术分享

4,详细代码
--- 首页 ViewController.swift ---
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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
            println("is goin")
            if group != nil
            {
                var assetBlock : ALAssetsGroupEnumerationResultsBlock = {
                    (result: ALAsset!, index: Int, stop) in
                    if result != nil
                    {
                        self.assets.append(result)
                        countOne++
                    }
                }
                group.enumerateAssetsUsingBlock(assetBlock)
                println("assets:\(countOne)")
                //collectionView网格重载数据
                self.collectionView?.reloadData()
            }
            }, failureBlock: { (fail) in
                println(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
             
            //取缩略图
            var myAsset = assets[indexPath.item]
            var 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跳转)
        var 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()
        // Dispose of any resources that can be recreated.
    }
}

--- 详情页 ImageDetailViewController.swift ---
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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()
         
        //获取文件名
        var 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))"
         
        //获取原图
        var imageBuffer = UnsafeMutablePointer<UInt8>.alloc(Int(representation.size()))
        var bufferSize = representation.getBytes(imageBuffer, fromOffset: Int64(0),
            length: Int(representation.size()), error: nil)
        var data =  NSData(bytesNoCopy:imageBuffer ,length:bufferSize, freeWhenDone:true)
        imageView.image = UIImage(data: data)
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

5,源码下载:技术分享PhotoViewer.zip

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

标签:

原文地址:http://www.cnblogs.com/Free-Thinker/p/4843339.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!