我在从iOS中的Photos框架中检索对象时遇到内存问题。我告诉你我的代码:
AVVideoScalingMode.ResizeAspectFill
Async是一个轻松管理public class func randomImageFromLibrary(
completion: @escaping (_ error: ImageProviderError?, _ image: UIImage?, _ creationDate: Date?, _ location: CLLocation?) -> Void) {
// Create the fetch options sorting assets by creation date
let fetchOptions = PHFetchOptions.init()
fetchOptions.sortDescriptors = [ NSSortDescriptor.init(key: "creationDate", ascending: true) ]
fetchOptions.predicate = NSPredicate.init(format: "mediaType == \(PHAssetMediaType.image)")
DispatchQueue.global(qos: .userInitiated).async {
let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil)
if fetchResult.count == 0 {
// The restoreAnimationAfterFetching method contains UI changes, this is why
// we perform this code on the main thread
Async.main({
print("No photos in the library!")
completion(.PhotoLibraryEmpty, nil, nil, nil)
})
return
}
var photos: [PHAsset] = []
// Enumerate the PHAssets present in the array and move everything to the photos array
fetchResult.enumerateObjects({ (object: PHAsset, index, stop: UnsafeMutablePointer<ObjCBool>) in
//let asset = object
photos.append(object)
})
let asset = photos[0] // This could be any number, 0 is only a test
// The options for the image request
// We want the HQ image, current version (edited or not), async and with the possibility to access the network
let options = PHImageRequestOptions.init()
options.deliveryMode = PHImageRequestOptionsDeliveryMode.highQualityFormat
options.version = PHImageRequestOptionsVersion.current
options.isSynchronous = false
options.isNetworkAccessAllowed = true
PHImageManager.default().requestImageData(
for: asset,
options: options,
resultHandler: { (imageData: Data?, dataUTI: String?, orientation: UIImageOrientation, info: [AnyHashable : Any]?) in
// If the image data is not nil, set it into the image view
if (imageData != nil) {
Async.main({
// Get image from the imageData
let image = UIImage.init(data: imageData!)
completion(nil, image, asset.creationDate, asset.location)
})
} else {
// TODO: Error retrieving the image. Show alert
print("There was an error retrieving the image! \n\(info![PHImageErrorKey])")
completion(.GenericError, nil, nil, nil)
}
}
)
}
}
的框架。
当我调用这个方法时,我的内存负载很重。如果我多次调用它,我可以看到仪器中的GCD
在不释放任何内容的情况下继续增加。我考虑过PHAsset
,但我不确定如何正确使用它。你有任何建议或类似的东西吗?最后一件事是我需要在今天的Widget中使用它,因为内存负载很重,它会不断崩溃。
答案 0 :(得分:0)
请注意,您正在使用该选项异步调用requestImageData:
isSynchronous = false
您可能不需要,因为调用代码已经在后台线程中。
这也意味着可以多次调用结果处理程序。并且与isNetworkAccessAllowed选项结合使用可能会延迟请求的完成和PHAsset实例的发布。
尝试:
isSynchronous = true
isNetworkAccessAllowed = false