[英]Memory management with Photos framework
我在從iOS中的Photos框架中檢索對象時遇到內存問題。 我告訴你我的代碼:
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)
}
}
)
}
}
Async是一個輕松管理GCD
的框架。 當我調用這個方法時,我的內存負載很重。 如果我多次調用它,我可以看到儀器中的PHAsset
繼續增加而不釋放任何東西。 我想過autoreleasepool
,但我不確定如何正確使用它。 你有任何建議或類似的東西嗎? 最后一件事是我需要在今天的Widget中使用它,因為內存負荷過重而不斷崩潰。
請注意,您正在使用該選項異步調用requestImageData:
isSynchronous = false
您可能不需要,因為調用代碼已經在后台線程中。
這也意味着可以多次調用結果處理程序。 並且與isNetworkAccessAllowed選項結合使用可能會延遲請求的完成和PHAsset實例的釋放。
試試:
isSynchronous = true
isNetworkAccessAllowed = false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.