Swift“希望对Array <any>进行解码,但找到了一个字典。”

时间:2019-04-03 19:59:08

标签: swift

我正在使用此代码从API提取数据,并在视图控制器中设置了一些变量,一切正常。由于我在多个控制器中执行此操作,因此我尝试使用完成处理程序将网络调用重构为Service类,以执行用于设置视图变量的必要代码。该服务在某些控制器上可以正常工作,但是任何尝试解码对象数组的控制器都会收到错误消息

  

typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“预期对Array进行解码,但找到了一个字典。”,底层错误:无))

工作

let httpURL = "https://myurl.com/api"
guard let url = URL(string: httpURL) else { return }
var request = URLRequest(url: url)

request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// Setting other headers here

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in        
    guard let data = data else {return}        
        do {
            let consults = try JSONDecoder().decode([Consultation].self, from:data)
                DispatchQueue.main.async {
                    // Settings values here
                    self.consultationTableView.reloadData()
                }            
            } catch let jsonErr {
                print(jsonErr)
            }        
        }
        task.resume()
}

不起作用

struct Service {
    static let sharedInstance = Service()

    func fetchPage(url: String, completion: @escaping (Data) -> ()){
        let httpURL = "https://myurl.com/api"

        guard let url = URL(string: httpURL) else { return }        
        var request = URLRequest(url: url)
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        // Other headers here        
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            guard let data = data else {return}

            completion(data)

        }
        task.resume()
    }
}

ViewController

        let httpURL = "https://myUrl.com/api"
        Service.sharedInstance.fetchPage(url: httpURL) { (data) in
            do {
                let consults = try 
 ---> Error Happens>> JSONDecoder().decode([Consultation].self, from:data)                 } 
            } catch let jsonErr {
                print(jsonErr)
            }
        }

有人知道为什么在使用服务类时会显示错误吗?

0 个答案:

没有答案