如何在Swift中将ALAsset转换为NSData?

时间:2015-10-07 14:35:22

标签: ios swift nsdata alasset

我尝试在以下代码中将ALAsset转换为NSData:

        let assetUrl = NSURL(string: self.filename!)

        ALAssetsLibrary().assetForURL(assetUrl,
            resultBlock: { asset in
                let rep = asset.defaultRepresentation()

                var buffer: UInt8 = UInt8()
                var error: NSError?

                let from: Int64 = 0

                let length: Int = Int(rep.size())
                var buffered = rep.getBytes(&buffer, fromOffset: from, length: length, error: &error)

                let data = NSData(bytesNoCopy: &buffered, length: length, freeWhenDone: true)

                self.video = data
            }, // # 1
            failureBlock: { error in
                println("ReportPhoto::loadVideoFromAssetsLibrary() - Error while loading saved video from AssetsLibrary!")
            }
        )

但是我在控制台中收到以下错误消息(代码中的#1):

object 0x27d02ce8: pointer being freed was not allocated

我跟踪了错误中提到的对象并找到了它,但我不知道是什么问题以及如何解决它!

该对象是名为NSData

_bytes对象内的属性

1 个答案:

答案 0 :(得分:4)

您的代码中存在两个问题:

  • rep.getBytes()将字节写入必须具有的现有缓冲区 已分配所需的大小。用你的缓冲区创建 var buffer: UInt8 = UInt8()的大小为零。
  • (正如@Lame已经在评论中说的那样:) rep.getBytes()的返回值 是写入缓冲区的字节数,而不是指向数据的指针。

最简单的方法是创建一个具有所需大小的NSMutableData对象 并将其可变数据指针传递给rep.getBytes()

var error: NSError?
let length = Int(rep.size())
let from = Int64(0)
let data = NSMutableData(length: length)!
let numRead = rep.getBytes(UnsafeMutablePointer(data.mutableBytes), fromOffset: from, length: length, error: &error)

另请注意,从iOS 9开始,不推荐使用ALAssetsLibrary框架。 如果您的最低部署目标是iOS 8或更高版本,那么您可以实现相同的目标 来自Photos框架的PHAssetPHImageManager

let fetchResult = PHAsset.fetchAssetsWithALAssetURLs([assetUrl!], options: nil)
if let phAsset = fetchResult.firstObject as? PHAsset {
    PHImageManager.defaultManager().requestImageDataForAsset(phAsset, options: nil) {
        (imageData, dataURI, orientation, info) -> Void in
        // ...
    }
}