如何在Swift中使用OperationQueue下载和解析JSON

时间:2017-12-28 21:32:15

标签: json swift nsoperationqueue

我已经陷入了一个概念上简单的问题。发生了什么是在下载操作的完成处理程序完成之前执行解析操作。因此,没有要解析的数据。您可以将以下代码直接放入文件中并运行它。

如何在解析操作运行之前确保下载完成?

import UIKit

let search = "https://api.nal.usda.gov/ndb/search/?format=json&q=butter&sort=n&max=25&offset=0&api_key=DEMO_KEY"

class ViewController: UIViewController {



    override func viewDidLoad() {
        super.viewDidLoad()

        let fetch = FetchNBDNumbersOperation()
        let parse = NDBParseOperation()

        // 1
        let adapter = BlockOperation() { [unowned parse, unowned fetch] in
            parse.data = fetch.data
        }

        // 2
        adapter.addDependency(fetch)
        parse.addDependency(adapter)

        // 3
        let queue = OperationQueue()
        queue.addOperations([fetch, parse, adapter], waitUntilFinished: true)
    }
}

class FetchNBDNumbersOperation: Operation {

    var data: Data?

    override func main() {
        let url = URL(string: search)!
        let urlSession = URLSession.shared
        let dataTask = urlSession.dataTask(with: url) { (jsonData, response, error) in
            guard let jsonData = jsonData, let response = response else {
                debugPrint(error!.localizedDescription)
                return
            }
            self.data = jsonData
            print("Response URL: \(String(describing: response.url?.absoluteString))")
        }
        dataTask.resume()
    }
}

class NDBParseOperation: Operation {

    var data: Data?
    var nbdNumbers = [NBDNumber]()

    override func main() {
        let decoder = JSONDecoder()
        do {
            guard let jsonData = self.data else {
                fatalError("No Data")
            }
            let dictionary = try decoder.decode( [String: USDAFoodSearch].self, from: jsonData )
            for (_, foodlist) in dictionary {
                for food in foodlist.item {
                    print("\(food.name) \(food.ndbno) \(food.group)")
                    let nbdNumber = NBDNumber(name: food.name, nbdNo: food.ndbno)
                    nbdNumbers.append(nbdNumber)
                }
            }
        } catch {
            print(error.localizedDescription)
        }
    }
}

struct NBDNumber {
    var name: String
    var nbdNo: String
}

struct USDAFoodSearch: Decodable {
    let q: String
    let sr: String
    let ds: String
    let start: Int
    let end: Int
    let total: Int
    let group: String
    let sort: String
    let item: [USDAFood]

    struct USDAFood: Decodable {
        let offset: Int     //Position in Array
        let group: String
        let name: String
        let ndbno: String
        let ds: String
    }
}

4 个答案:

答案 0 :(得分:1)

在您的提取操作中,您将恢复URLSessionDataTask。此时,操作认为它已完成,因为它不知道在其他线程上发生了什么,并且本身并不关心并发操作,而且#&#&# 39; s依赖(adapter)开始。与此同时,URLSessionDataTask仍然在另一个线程上执行。

来自Apple在NSOperation

上的文档
  

对于非并发操作,通常只覆盖一个方法:

     
      
  • main()
  •   

URLSessionDataTask并发运行,因此您需要做更多工作才能将它们包装在NSOperation中。为了包装并发操作,您需要:

  

...至少覆盖以下方法和属性:

     

start()

     

isAsynchronous

     

isExecuting

     

isFinished

NSOperation docs详细介绍了这一点,但总结一下:您需要覆盖start()而不是main()并让您的实施保留操作状态是最新的。

答案 1 :(得分:1)

您只是使用main操作队列方法 并且您没有通知操作队列有关操作状态的信息

由于 jjatie Operation Queue需要 isExecuting isFinished KVC来通知队列有关已完成或正在执行的操作

我的建议是,在进行如此复杂的操作之前,请先阅读文档。

这是一个示例代码

class WSOperations: Operation {

    private var _executing = false
    private var _finished = false
    private var showHUD:HUDFlag = .show

    override var isExecuting: Bool {
        get {
            return _executing
        } set {
            willChangeValue(forKey: "isExecuting")
            _executing = newValue
            didChangeValue(forKey: "isExecuting")

        }

    }

    override var isFinished: Bool {
        get {
            return _finished
        } set {
            willChangeValue(forKey: "isFinished")
            _finished = newValue
            didChangeValue(forKey: "isFinished")
        }
    }



    override func start() {
        if isCancelled {
            isFinished = true

            return
        }

        isExecuting = true

        func completeOperation() {
            isFinished = true
            isExecuting = false
            Logger.log(message: "Operation finished")
        }

        //Your request
           request =  DataManager.sharedManager.getRequest(showHUD: showHUD, success: { (success, response) in
                if let t = self.finishedBLock {
                    t.success(success, response)
                }
                completeOperation()
            }, failure: { (error) in
                if let t = self.finishedBLock {
                    t.failure(error)
                }
                completeOperation()

            })


    }
    override func cancel() {
        super.cancel()
        if isExecuting {
            isFinished = true
            isExecuting = false
        }

        request?.cancel()
    }
}

希望它对你有所帮助

答案 2 :(得分:0)

您过度复杂,甚至不需要使用OperationQueue,因为数据任务将异步完成。

你可以这样做:

class FetchAndParse {
    var data: Data?
    var nbdNumbers = [NBDNumber]()

    func fetch() {
        let url = URL(string: search)!
        let urlSession = URLSession.shared
        let dataTask = urlSession.dataTask(with: url) { (jsonData, response, error) in
            guard let jsonData = jsonData, let response = response else {
                debugPrint(error!.localizedDescription)
                return
            }
            self.data = jsonData
            print("Response URL: \(String(describing: response.url?.absoluteString))")

            self.parse()
        }
        dataTask.resume()
    }

    func parse() {
        let decoder = JSONDecoder()
        do {
            guard let jsonData = self.data else {
                fatalError("No Data")
            }
            let dictionary = try decoder.decode( [String: USDAFoodSearch].self, from: jsonData )
            for (_, foodlist) in dictionary {
                for food in foodlist.item {
                    print("\(food.name) \(food.ndbno) \(food.group)")
                    let nbdNumber = NBDNumber(name: food.name, nbdNo: food.ndbno)
                    nbdNumbers.append(nbdNumber)
                }
            }
            print ("Finished With \(nbdNumbers.count) Items")
        } catch {
            print(error.localizedDescription)
        }
    }
}

然后你可以这样使用:

let fp = FetchAndParse()
print ("Before Fetch")
fp.fetch()
print ("After Fetch")

如果你跑步,你会看到'之前取得'和'取回后'消息在下载和解析完成之前显示,并且在正确获取之后发生解析。

当然你可能需要更新它,以便课程通知一切都完整,所以可能是一个完成处理程序或委托,但我会把它留给你。

答案 3 :(得分:0)

这是答案。子类使用下面的类获取操作。告诉它操作在Fetch Op完成处理程序结束时完成。

Function.prototype.call

在此处找到异步子类:https://gist.github.com/Sorix/57bc3295dc001434fe08acbb053ed2bc

class FetchNBDNumbersOperation: AsynchronousOperation {

    var data: Data?

    override func main() {
        super.main()

        let url = URL(string: search)!
        let urlSession = URLSession.shared
        let dataTask = urlSession.dataTask(with: url) { (jsonData, response, error) in
            guard let jsonData = jsonData, let response = response else {
                debugPrint(error!.localizedDescription)
                return
            }
            self.data = jsonData
            print("Response URL: \(String(describing: response.url?.absoluteString))")
            self.state = .finished
        }
        dataTask.resume()
    }
}