我正在try 从用户的照片库中获取一些照片(PHAsset张),并将它们转换为UIImage张.

以下是从库中获取assets资源 的代码:

     func fetchPhotos() {
        
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "(mediaSubtype & %d) != 0", PHAssetMediaSubtype.photoScreenshot.rawValue)
        
        //Fetching Screen Shots
        fetchedResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
        
        let f: FetchResult = FetchResult(fetchedResult!)
        var fetchCount = 0
        
        for i in f {
            fetchCount += 1
            print("Fetch count \(fetchCount)")
            let img = i.getAssetThumbnail()
            testImages.append(img)
        }
    }

以下是满分为PHAsset分的代码:

extension PHAsset {
    func getAssetThumbnail() -> UIImage {
        let manager = PHImageManager.default()
        let option = PHImageRequestOptions()
        var thumbnail = UIImage()
        option.isSynchronous = true
        manager.requestImage(for: self,
                             targetSize: CGSize(width: self.pixelWidth, height: self.pixelHeight),
                             contentMode: .aspectFit,
                             options: option,
                             resultHandler: {(result, info) -> Void in
                                thumbnail = result!
                             })
            return thumbnail
    }
}

我当前在try 运行代码时得到以下崩溃输出:

Details

The app “AppClassificationDemo” on Nick’s iPhone quit unexpectedly.
Domain: IDEDebugSessionErrorDomain
Code: 11
Failure Reason: Message from debugger: Terminated due to memory issue
User Info: {
    DVTErrorCreationDateKey = "2022-11-14 22:19:19 +0000";
    IDERunOperationFailingWorker = DBGLLDBLauncher;
}
--

Analytics Event: com.apple.dt.IDERunOperationWorkerFinished : {
    "device_model" = "iPhone14,2";
    "device_osBuild" = "16.1.1 (20B101)";
    "device_platform" = "com.apple.platform.iphoneos";
    "launchSession_schemeCommand" = Run;
    "launchSession_state" = 2;
    "launchSession_targetArch" = arm64;
    "operation_duration_ms" = 6369;
    "operation_errorCode" = 11;
    "operation_errorDomain" = IDEDebugSessionErrorDomain;
    "operation_errorWorker" = DBGLLDBLauncher;
    "operation_name" = IDEiPhoneRunOperationWorkerGroup;
    "param_consoleMode" = 0;
    "param_debugger_attachToExtensions" = 0;
    "param_debugger_attachToXPC" = 1;
    "param_debugger_type" = 5;
    "param_destination_isProxy" = 0;
    "param_destination_platform" = "com.apple.platform.iphoneos";
    "param_diag_MainThreadChecker_stopOnIssue" = 0;
    "param_diag_MallocStackLogging_enableDuringAttach" = 0;
    "param_diag_MallocStackLogging_enableForXPC" = 1;
    "param_diag_allowLocationSimulation" = 1;
    "param_diag_checker_tpc_enable" = 1;
    "param_diag_gpu_frameCapture_enable" = 0;
    "param_diag_gpu_shaderValidation_enable" = 0;
    "param_diag_gpu_validation_enable" = 0;
    "param_diag_memoryGraphOnResourceException" = 0;
    "param_diag_queueDebugging_enable" = 1;
    "param_diag_runtimeProfile_generate" = 0;
    "param_diag_sanitizer_asan_enable" = 0;
    "param_diag_sanitizer_tsan_enable" = 0;
    "param_diag_sanitizer_tsan_stopOnIssue" = 0;
    "param_diag_sanitizer_ubsan_stopOnIssue" = 0;
    "param_diag_showNonLocalizedStrings" = 0;
    "param_diag_viewDebugging_enabled" = 1;
    "param_diag_viewDebugging_insertDylibOnLaunch" = 1;
    "param_install_style" = 0;
    "param_launcher_UID" = 2;
    "param_launcher_allowDeviceSensorReplayData" = 0;
    "param_launcher_kind" = 0;
    "param_launcher_style" = 0;
    "param_launcher_substyle" = 0;
    "param_runnable_appExtensionHostRunMode" = 0;
    "param_runnable_productType" = "com.apple.product-type.application";
    "param_runnable_type" = 2;
    "param_testing_launchedForTesting" = 0;
    "param_testing_suppressSimulatorApp" = 0;
    "param_testing_usingCLI" = 0;
    "sdk_canonicalName" = "iphoneos16.1";
    "sdk_osVersion" = "16.1";
    "sdk_variant" = iphoneos;
}
--


System Information

macOS Version 13.0.1 (Build 22A400)
Xcode 14.1 (21534.1) (Build 14B47b)
Timestamp: 2022-11-14T14:19:19-08:00

我相当确定它是要生成的图像缩略图的大小;当我将widthheight都设置为width时,处理工作就像预期的那样.

当将其更改为self.pixelWidthself.pixelHeight时,应用程序会崩溃.

推荐答案

不要试图将PHAsset转换为UIImage并存储在数组中.因为UIImage将使用图像的全部内存大小.因此,数组中的图像太多会导致内存泄漏.

因此,只需按需获取所需的PHAsset,并在需要时请求UIImage.请参见下面的示例.

func loadImageAt(_ index:Int) -> UIImage?{
            
    let asset = fetchResult.object(at: index)
    
    let manager = PHImageManager.default()
    let option = PHImageRequestOptions()
    
    var thumbnail:UIImage?
    
    option.isSynchronous = true
    manager.requestImage(for: asset,
                         targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight),
                         contentMode: .aspectFit,
                         options: option,
                         resultHandler: {(result, info) -> Void in
        
        thumbnail = result
    })
    
    return thumbnail
}

另外,我还建议您使用异步图像请求来避免UI性能问题.

希望这个能帮上忙!

Ios相关问答推荐

如何正确测试后台URLSessionDownloadTask?

更新Flutter项目时出错:CocoaPods找不到pod webview_flutter_wkwebview的兼容版本""

快速相机放大手势不能正常工作

为什么iOS委派在KMM中不能正常工作?

如何使用 SwiftData 从列表中删除子项目?

在 iOS 上启用明文本地流量在 .NET MAUI 中不起作用

Flutter Aging Person 自定义小部件

当 Swift 枚举具有 any existential 作为其关联值之一时,我如何使它符合 `Equatable`?

为什么这个 SwiftUI 状态在作为非绑定参数传递时没有更新?

SwiftUI 动画:为什么容器视图在移动?我很难理解这种行为

如何让我的 iOS 应用程序与 api 连接?

SignalR 永远不会在 iOS 上使用 Xamarin Forms 启动

禁用 UITextField 的自动更正

如何使用 Swift 文档注释

如何确定 WKWebView 的内容大小?

如何从 UIPickerView 获取选定的值

UICollectionView:必须用非零布局参数初始化

iPhone UITableView.如何开启音乐 App 之类的单字母字母列表?

在自动布局中居中子视图的 X 会引发未准备好约束

这是一个什么样的讽刺错误?