DownloadGroup意外阻止网络通话

时间:2019-04-18 02:46:38

标签: ios swift grand-central-dispatch nsurlsession

我正在从指令列表中更新用户数据库。如果有新照片要下载,我将调用一个单独的函数并为每张照片发送一个URL请求,然后希望使用补全对调用函数说所有照片均已下载。我通过coreDataStack.storeContainer.performBackgroundTask用新的NSManagedObjectContext调用此函数。

我正在使用for循环遍历URL,并认为使用DispatchGroup可以确保在调用完成之前我成功下载了所有照片。

我一直在使用wait(超时:),超时时间为30秒。我可以成功输入该函数来请求单张照片,但是URLSession.shared.datatask仅在超时触发时恢复!

我显然对DispatchGroup做错了,但是我在其他地方用过它,看不出问题出在哪里:/

func updatePhotoOrImage(moContext: NSManagedObjectContext, idsNeedingPhotoOrImageUpdate: [(Int, Bool)], completion: @escaping (_ success: Bool) -> Void) {
        let downloadGroup = DispatchGroup()
        for (onlineID, isPerson) in idsNeedingPhotoOrImageUpdate {
            if isPerson {
                let personFromID = AdministrativeHelperFunctions.findPersonFromOnlineID(onlineID: onlineID, moContext: moContext)
                if let personFromID = personFromID {
                    if let urlString = personFromID.urlString {
                        downloadGroup.enter()
                        NetworkHelperFunctions.retrieveAndSavePhotoFromOnline(urlString: urlString, moContext: moContext, person: personFromID) { _ in
                            downloadGroup.leave()
                        }
                    }
                }
            } else {
                let bookEntryFromID = AdministrativeHelperFunctions.findbookEntryFromOnlineID(onlineID: onlineID, moContext: moContext)
                    if let bookEntryFromID = bookEntryFromID {
                        if let urlString = bookEntryFromID.imageURLString {
                            downloadGroup.enter()
BookNetworkFunctions.retrieveAndSaveImageFromOnline(urlString: urlString, moContext: moContext, bookEntry: bookEntryFromID) { _ in
                           downloadGroup.leave()
                            }
                        }
                    }
                }
            }

        let result = downloadGroup.wait(timeout: .now() + 30)
        if result == .timedOut {
            print("TimedOut")
        }
        completion(true)
    }

public class func retrieveAndSavePhotoFromOnline(urlString: String, moContext: NSManagedObjectContext, person: Person, completion: @escaping (Bool) -> Void) {
        let photoURL = URL(string: urlString)
        if let photoURL = photoURL {
            let task = URLSession.shared.dataTask(with: photoURL) { (data, response, error) in
                    if let data = data {
                        person.photoData = data as NSData
                        completion(true)
                    } else {
                        completion(false)
                    }
                }
            }
            task.resume()
        } else {
            completion(false)
        }
    }

基本上,我想在所有照片返回后保存上下文。就这样,等待超时,保存上下文(对于嵌套函数中的其他内容),然后URLSession立即触发并返回照片!

任何帮助将不胜感激。

0 个答案:

没有答案