ios - 使用 for 循环下载图像并保存到核心数据
问题描述
我目前有一个用于从存储在数组中的 url 下载图像的 for 循环。每获取 2 或 3 个新图像后,我总是遇到相同图像的问题。每次我获取新图像时,我都可以看到它使用不同的 url 来下载图像,但数组中的图像是相同的。
这是我的代码如下:
func downloadImageDetailsFromFlickr(completion: @escaping (Bool, Error?) -> Void) {
self.imageLoading(is: true)
flickrClient.getImageDetailsFromFlickr(lat: latitude, lon: longitude) { (photo, error) in
if error == nil {
self.photoStore = []
for image in photo {
if image.url_m.count == 0 {
self.imageLabel.isHidden = false
self.imageLoading(is: false)
completion(false, nil)
} else {
self.photoStore.append(image.url_m)
print(self.photoStore)
completion(true, nil)
}
}
} else {
print(error?.localizedDescription ?? "Error in the fetch image block")
print("problem in downloading details.")
completion(false, error)
}
}
}
func downloadImage(completion: @escaping(Bool, Error?) -> Void ) {
let flickrImage = FlickrImage(context: self.dataController.viewContext)
for flickr in photoStore {
self.photoUrl = ""
self.photoUrl = flickr
}
flickrClient.getImage(imageUrl: photoUrl ?? "") { (data, error) in
if error == nil {
self.imageLoading(is: false)
flickrImage.photo = data
flickrImage.url = self.photoUrl
flickrImage.locations = self.location
flickrImage.locations?.latitude = self.latitude
flickrImage.locations?.longitude = self.longitude
}
else {
print(error?.localizedDescription ?? "Something went wrong downloading an image")
}
do {
try self.dataController.viewContext.save()
self.photoStore.removeAll()
completion(true, nil)
} catch {
print("Error saving into Core Data")
completion(false, error)
}
}
}
请忽略红框,白框表示重新获取的图像。我的猜测是,它与核心数据有关。
解决方案
我不确定这是否能解决您的问题,但是,您是否可以尝试使用 dispatchgroup()
所以它会像这样
let group = DispatchGroup()
for flickr in photoStore {
//fetch image from url here
group.enter()
flickrClient.getImage(imageUrl: flickr ?? "") { (data, error) in
if error == nil {
self.imageLoading(is: false)
flickrImage.photo = data
flickrImage.url = self.photoUrl
flickrImage.locations = self.location
flickrImage.locations?.latitude = self.latitude
flickrImage.locations?.longitude = self.longitude
group.leave()
}
else {
print(error?.localizedDescription ?? "Something went wrong downloading an image")
group.leave()
}
}
group.notify(queue: .main) { [weak self] in
//save your dowloaded image here
try self?.dataController.viewContext.save()
self?.photoStore.removeAll()
} catch {
print("Error saving into Core Data")
}
}
所以基本上通过使用 dispatchgroup 你可以对任务进行分组并异步运行它。它只是为了确保请求不会重复,并且您将图像保存到核心数据一次。
推荐阅读
- scala - Spark Scala UDAF 用于 n 天的滚动计数
- azure-resource-manager - 在 VMSS 中的不同订阅下使用来自多个 KeyVault 的证书/密钥
- ansible - ansible - 块条件被忽略
- android - Kotlin Room 找不到字段的吸气剂
- php - 为什么每次运行我的登录序列后我的 php $_POST 和 $_SESSION 都没有清除?
- javascript - node.js 中函数的默认对象命名空间是什么?
- sql - 如何在 postgres 中选择 json 数组的大小?
- file-rename - 如何在 Alpine 上安装 perl rename?
- android - 看不到回收站视图
- c# - C# 自动化测试在执行所有逻辑之前无错误退出