将多个图像下载到CoreData中

问题描述

我正在用Swift编写iOS应用。

在我的主页( HomeLandingViewController.swift )中,我必须调用两个并行的API,这给了我一张图像列表,我必须下载所有这些图像,然后转储到CoreData中。直到此过程完成,我必须在UI中显示一些加载动画等。

流量:

主页VC加载>开始动画>并行调用API 1和Call API 2>从API 1和API 2接收图像数组>获取所有这些图像的数据>转储到Coredata>通知主页VC完成>停止动画

为此,我制作了一个专用的类( IconsHelper.swift

我正在使用Moya网络库。

问题在于事情没有按预期进行。由于事情是异步进行的,因此即使在下载图像之前,主页VC也会收到通知

我的代码段:

IconsHelper.shared.getNewIconsFromServer()

class IconsHelper {
    static let shared: IconsHelper = .init()
    
    var group:dispatchGroup?

    //Get Icons from API 1 and API 2:
    func getNewIconsFromServer() {
        group = dispatchGroup()
        group?.enter()
        
        let dispatchQueue_amc = dispatchQueue(label: "BackgroundIconsFetch_AMC",qos: .background)
        
        dispatchQueue_amc.async(group: group) {
            self.getNewIcons(type: .amcIcons)
        }
        
        if group?.hasGroupValue() ?? false {
            group?.leave()
            Log.b("CMSIcons: Group Leave 1")
        }
        
        group?.enter()
        
        let dispatchQueue_bank = dispatchQueue(label: "BackgroundIconsFetch_Bank",qos: .background)
        dispatchQueue_bank.async(group: group) {
            self.getNewIcons(type: .bankIcons)
        }
        
        if group?.hasGroupValue() ?? false {
            group?.leave()
            Log.b("CMSIcons: Group Leave 2")
        }
        
        group?.notify(queue: .global(),execute: {
            Log.b("CMSIcons: All icons fetched from server.")
        })
    }

    func getNewIcons(type: CMSIconsTypes) {
        let iconsCancellabletoken: Cancellabletoken?
        
        let progressClosure: ProgressBlock = { response in
        }
        
        let activityChange: (_ change: NetworkActivityChangeType) -> Void = { (activity) in
            
        }
        
        let cmsCommonRequestType=self.getCmsCommonRequestType(type: type)
        
        iconsCancellabletoken = CMSProvider<CMSCommonResponse>.request( .cmsCommonRequest(request: cmsCommonRequestType),success: { (_response) in
            Log.b("CMSIcons: Get new icons from server for type: \(type)")
            
            //Set http to https:
            var iconsHostname:String=""{
                didSet {
                    if let comps=URLComponents(string: iconsHostname) {
                        var _comps=comps
                        _comps.scheme = "https"
                        if let https = _comps.string {
                            iconsHostname=https
                        }
                    }
                }
            }
            
            if (_response.data?.properties != nil) {
                if _response.status {
                    
                    let alias = self.getCmsAlias(type: type)
                    let property = _response.data?.properties.filter {$0.alias?.lowercased()==ValueHelper.getCMSAlias(alias)}.first?.value
                    
                    if let jsonStr = property {
                        iconsHostname = _response.data?.hostName ?? ""
                        
                        if let obj:CMSValuesResponse = CMSValuesResponse.map(JSONString: jsonStr) {
                            
                            if let fieldsets=obj.fieldsets {
                                if fieldsets.count > 0 {
                                    for index in 1...fieldsets.count {
                                        let element=fieldsets[index-1]
                                        if let prop = element.properties {
                                            if(prop.count > 0) {
                                                let urlAlias = self.getCmsURLAlias(type: type)
                                                
                                                let iconUrl = prop.filter {$0.alias?.lowercased()==ValueHelper.getCMSAlias(urlAlias)}.first?.value
                                                
                                                let name = prop.filter {$0.alias?.lowercased()==ValueHelper.getCMSAlias(.iconsNameAlias)}.first?.value
                                                
                                                if let iconUrl=iconUrl,let name=name {
                                                    if let url = URL(string: iconsHostname+iconUrl) {
                                                        dispatchQueue.global().async {
                                                            if let data = try? Data(contentsOf: url) {
                                                                Log.b("CMSIcons: Icon url \(url.absoluteString) to Data done.")
                                                                var databaseDumpObject=CMSIconStructure()
                                                                databaseDumpObject.name=name
                                                                databaseDumpObject.data=data
                                                                self.dumpIconToLocalStorage(object: databaseDumpObject,type: type)
                                                                
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }//Loop ends.
                                    //After success:
                                    self.setFetchIconsDateStamp(type:type)
                                }
                            }
                        }
                    }
                }
            }
            
        },error: { (error) in
            
        },failure: { (_) in
            
        },progress: progressClosure,activity: activityChange) as? Cancellabletoken
        
    }

    //Dump icon data into CoreData:
    func dumpIconToLocalStorage(object: CMSIconStructure,type: CMSIconsTypes) {
        let entityName =  self.getEntityName(type: type)
        
        if #available(iOS 10.0,*) {
            Log.b("Do CoreData task in background thread")
            //Do CoreData task in background thread:
            
            let context = appDelegate().persistentContainer.viewContext
            let privateContext: NSManagedobjectContext = {
                let moc = NSManagedobjectContext(concurrencyType: .privateQueueConcurrencyType)
                moc.parent = context
                return moc
            }()
            
            //1: Read all offline Icons:
            let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
            
            fetchRequest.predicate = nspredicate(format: "name = %@",argumentArray: [object.name.lowercased()])
            
            do {
                let results = try privateContext.fetch(fetchRequest) as? [NSManagedobject]
                if results?.count != 0 {
                    //2: Icon already found in CoreData:
                    
                    if let icon=results?[0] {
                        icon.setValue(object.name.lowercased(),forKey: "name") //save lowercased
                        icon.setValue(object.data,forKey: "data")
                    }
                    
                } else {
                    //3: Icon not found in CoreData:
                    
                    let entity = NSEntityDescription.entity(forEntityName: entityName,in: privateContext)
                    let newIcon = NSManagedobject(entity: entity!,insertInto: privateContext)
                    newIcon.setValue(object.name.lowercased(),forKey: "name") //save lowercased
                    newIcon.setValue(object.data,forKey: "data")
                    
                }
                
                Log.b("CMSIcons: Icon data saved locally against name: \(object.name)")
                
            } catch {
                Log.i("Failed reading CoreData \(entityName.uppercased()). Error: \(error)")
            }
            privateContext.perform {
                // Code in here is Now running "in the background" and can safely
                // do anything in privateContext.
                // This is where you will create your entities and save them.
                
                do {
                    try privateContext.save()
                } catch {
                    Log.i("Failed reading CoreData \(entityName.uppercased()). Error: \(error)")
                }
            }
        } else {
            // Fallback on earlier versions
        }
    }
}

解决方法

通常不建议将图像作为二进制数据存储在Core Data持久存储中。而是将图像写入本地目录,然后将本地URL存储在核心数据中。这是一个示例工作流程,可以使用此推荐方法简化您遇到的一些问题:

class IconsHelper {
    
    let container: NSPersistentContainer
    let provider: CMSProvider<CMSCommonResponse>
    private let queue: DispatchQueue = DispatchQueue(label: "IconsHelper",qos: .userInitiated)
    
    let documentsDirectory: URL = {
        let searchPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)
        guard let path = searchPath.last else {
            preconditionFailure("Unable to locate users documents directory.")
        }
        
        return URL(fileURLWithPath: path)
    }()
    
    init(container: NSPersistentContainer,provider: CMSProvider<CMSCommonResponse>) {
        self.container = container
        self.provider = provider
    }
    
    enum Icon: String,Hashable {
        case amc
        case bank
    }
    
    func getIcons(_ icons: Set<Icon>,dispatchQueue: DispatchQueue = .main,completion: @escaping ([Icon: URL]) -> Void) {
        queue.async {
            var results: [Icon: URL] = [:]
            
            guard icons.count > 0 else {
                dispatchQueue.async {
                    completion(results)
                }
                return
            }
            
            let numberOfIcons = icons.count
            var completedIcons: Int = 0
            
            for icon in icons {
                let request = [""] // Create request for the icon
                self.provider.request(request) { (result) in
                    switch result {
                    case .failure(let error):
                        // Do something with the error
                        print(error)
                        completedIcons += 1
                    case .success(let response):
                        // Extract information from the response for the icon
                        
                        let imageData: Data = Data() // the image
                        let localURL = self.documentsDirectory.appendingPathComponent(icon.rawValue + ".png")
                        
                        do {
                            try imageData.write(to: localURL)
                            try self.storeURL(localURL,forIcon: icon)
                            results[icon] = localURL
                        } catch {
                            print(error)
                        }
                        
                        completedIcons += 1
                        
                        if completedIcons == numberOfIcons {
                            dispatchQueue.async {
                                completion(results)
                            }
                        }
                    }
                }
            }
        }
    }
    
    func storeURL(_ url: URL,forIcon icon: Icon) throws {
        // Write the local URL for the specific icon to your Core Data Container.
        let context = container.newBackgroundContext()
        
        // Locate & modify,or create CMSIconStructure using the context above.
        
        try context.save()
    }
}

然后在您的首页视图控制器中:

// Display Animation

let helper: IconsHelper = IconsHelper.init(container: /* NSPersistentContainer */,provider: /* API Provider */)
helper.getIcons([.amc,.bank]) { (results) in
    // Process Results
    // Hide Animation
}

这里的一般设计是只有一个调用,该调用将处理图像的下载和处理,然后在所有网络调用和核心数据交互完成之后响应结果。

在示例中,您将使用对CoreData NSPersistentContainer和网络实例的引用来初始化IconsHelper。这种方法是否有助于弄清为什么示例代码无法按预期方式工作?