如何在后台全局队列中运行一堆任务

时间:2019-03-13 18:25:59

标签: ios swift grand-central-dispatch

在以下代码中,我想向服务器发送一些值,并更新选项卡上的徽章编号。一连串的操作从markRead()启动,在这里我从服务器获取值,完成后,我会更新选项卡上的徽章编号。

我觉得整个操作应该在后台队列中执行。我不确定如何在后台将任务发送到何处,然后返回主队列以更新徽章编号。

有帮助吗?

class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool){
        super.viewWillAppear(animated)

        // I want to send following in the background queue
        self.markRead(senderId: self.psychicId)

        // Continue to do other stuff...

    }

    func markRead(senderId: Int) {

        fetchMarkRead(jsonObject: jsonObject) { (result, error) in
            guard error == nil else {
                return
            }

            if (result?.success)! {
                self.updateBadges { () -> () in
                }
            }
        }
    }

    func markRead(jsonObject:[String:Any], _ completed: @escaping ((_ result: MarkAsReadRoot?, _ error: Error?) -> Void)) {

        // construct url, josn etc...

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                completed( nil,error)
                return
            }
            guard let httpResponse = response as? HTTPURLResponse,
                (200...299).contains(httpResponse.statusCode) else {
                    completed( nil,"Error in getting data from server" as? Error)
                    return
            }

            do {
                let resultData = try JSONDecoder().decode(MarkAsReadRoot.self, from: data)
                completed( resultData,nil)
            } catch let jsonError {
                completed(nil,jsonError)
                return
            }
        }
        task.resume()
    }

    func updateBadges(completed:@escaping (()->())){
        // Get values from server
        // Set badge number on Tabs
    }

}

0 个答案:

没有答案