首页 > 解决方案 > 使用 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)
                }
            }
}

请忽略红框,白框表示重新获取的图像。我的猜测是,它与核心数据有关。

在此处输入图像描述

标签: iosswiftcore-datauicollectionviewnsfetchedresultscontroller

解决方案


我不确定这是否能解决您的问题,但是,您是否可以尝试使用 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 你可以对任务进行分组并异步运行它。它只是为了确保请求不会重复,并且您将图像保存到核心数据一次。


推荐阅读