swift 无法推断泛型参数“Parameters”

6l7fqoea  于 2023-06-28  发布在  Swift
关注(0)|答案(1)|浏览(120)

无法从API获取数据。

class GetData{

static let sharedInstance = GetData()

func callingGetAPI() {
    
let url = "https://jsonplaceholder.typicode.com/posts"
   
    AF.request(url, method: .get, parameters: nil, encoder: JSONParameterEncoder.default, headers: nil,interceptor: nil).response{
            responce in
        debugPrint(responce)
        switch responce.result{
        case .success(let data):
            do{
                let json = try JSONDecoder().decode([Model].self, from: data!)
                print(json)
            }catch{
                print( "Please Try again")
              //  completionHandler(.failure(.custom(message: "Please Try again")))
            }
        case .failure(let err):
            print(err.localizedDescription)
            print( "Please Try again")
        }


    }
}

}


struct Model:Codable {
let userId:Int
let id:Int
let title : String
let body: String
 }
omtl5h9j

omtl5h9j1#

您可以将上面的AF请求替换为下面的,它使用参数编码而不是编码器。

func callingGetAPI() {
    
    let url = "https://jsonplaceholder.typicode.com/posts"
    
    AF.request(url,
               method: .get,
               encoding: JSONEncoding.prettyPrinted,
               headers: nil,
               interceptor: nil).response { response in
        debugPrint(response)
        
        switch response.result{
        case .success(let data):
            do{
                let json = try JSONDecoder().decode([Model].self, from: data!)
                print(json)
            }catch{
                print( "Please Try again")
                //  completionHandler(.failure(.custom(message: "Please Try again")))
            }
        case .failure(let err):
            print(err.localizedDescription)
            print( "Please Try again")
        }
    }
}

相关问题