提问人:S A 提问时间:8/26/2020 最后编辑:richardpiazzaS A 更新时间:8/27/2020 访问量:246
将多个图像下载到 CoreData 中
Download multiple images into CoreData
问:
我正在用 Swift 编写一个 iOS 应用程序。
在我的主页(HomeLandingViewController.swift)中,我必须并行调用两个 API,这给了我一个图像列表,我必须下载所有这些图像,然后转储到 CoreData 中。在此过程完成之前,我必须在UI中显示一些加载动画等。
流:
主页 VC 加载 >启动动画 > 调用 API 1 和调用 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
}
}
}
答:
1赞
richardpiazza
8/27/2020
#1
通常不建议将图像作为二进制数据存储在 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。这种方法是否有助于阐明为什么您的示例代码无法按预期方式工作?
下一个:如何解决核心数据崩溃?
评论