SWIFT ALAssetsLibrary不枚举组

时间:2014-08-07 20:26:12

标签: ios swift closures enumeration alassetslibrary

我正在尝试将所有用户图像的缩略图收集到一个数组中,但是当我调用enumerateAssetsUsingBlock ALAssetsLibrary方法时似乎没有任何事情发生。

import UIKit
import AssetsLibrary

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate  {


@IBOutlet var photoLibView: UICollectionView
var assetLibrary : ALAssetsLibrary = ALAssetsLibrary()


func showCustomLibrary() {
    self.assetLibrary = ALAssetsLibrary()

    var assetsArray : [ALAsset] = []
    var imageArray : [CGImage] = []
    var count = 0
    var countOne = 0
    let assetsType : ALAssetsGroupType = Int(ALAssetsGroupAll)

    var groupBlock : ALAssetsLibraryGroupsEnumerationResultsBlock = {

        (group: ALAssetsGroup!, stop: UnsafePointer<ObjCBool>) in
        println("is goin")
        count++
        var assetBlock : ALAssetsGroupEnumerationResultsBlock = {
            (result: ALAsset!, index: Int, stop: UnsafePointer<ObjCBool>) in
            imageArray.append(result.thumbnail().takeRetainedValue())
            assetsArray.append(result)
            countOne++
        }

        group.enumerateAssetsUsingBlock(assetBlock)


    }
    var groupFailureBlock : ALAssetsLibraryAccessFailureBlock = {
        (NSError) in
        println("errorrrrrrrr")

    }
    assetLibrary.enumerateGroupsWithTypes(assetsType, usingBlock: groupBlock, failureBlock: groupFailureBlock)



    println("number of groups")
    println(count)
    println("number of total assets")
    println(countOne)

    self.photoLibView.insertItemsAtIndexPaths(imageArray)


}


}

当我运行showCustomLibrary()时,编译器会打印number of groups 0 number of total assets 0 fatal error: unexpectedly found nil while unwrapping an Optional value 因为似乎没有枚举ALAssetsLibrary的组。 (“是goin”没有打印)。知道这里发生了什么吗?提前谢谢!

2 个答案:

答案 0 :(得分:2)

我发现了这个问题。 在这个“组”中,结果不应该是零,否则它会迅速崩溃。 所以我们应该检查零案例 像

var groupBlock : ALAssetsLibraryGroupsEnumerationResultsBlock = {

    (group: ALAssetsGroup!, stop: UnsafePointer<ObjCBool>) in
    println("is goin")
    if group != nil
    {
        count++
         var assetBlock : ALAssetsGroupEnumerationResultsBlock = {
            (result: ALAsset!, index: Int, stop: UnsafePointer<ObjCBool>) in
            if result != nil
            {
             imageArray.append(result.thumbnail().takeRetainedValue())
             assetsArray.append(result)
             countOne++
            }
        }
    }

    group.enumerateAssetsUsingBlock(assetBlock)


}

答案 1 :(得分:0)

我遇到的问题是,截断的代码返回0表示部分的数量,因此我将其更改为1,至少对于我正在处理的示例:https://github.com/thegreatmichael/Albums-iOS8-Swift/blob/master/Albums/IAAlbumsViewController.swift#L66