mazenqp
mazenqp

Reputation: 355

request an AlamoFire url using swift 5

I just found this method writing way back I change AlamoFire.request to AF.request & .responseSwiftyJSON { (dataResponse) in to .responseJSON(completionHandler: { (dataResponse) in I did copy it but I'm trying to use it, I'm not familiar with alamoFire this is the first time I'm using it can anyone update this method for requesting a URL from AlamoFire I'm just facing these errors

1- isSuccess' is inaccessible due to 'internal' protection level

2- Value of type 'Result' has no member 'value'

3- isFailure' is inaccessible due to 'internal' protection level

4- Value of type 'Result' has no member 'error'

@objc func searchPlaces(query: String) {
        let urlStr = "\(MapBox.mapbox_api)\(query).json?access_token=\(MapBox.mapbox_access_token)"

        AF.request(urlStr, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON(completionHandler: { (dataResponse) in

            if dataResponse.result.isSuccess {
                let resJson = JSON(dataResponse.result.value!)
                if let myjson = resJson["features"].array {
                    for itemobj in myjson ?? [] {
                        try? print(itemobj.rawData())
                        do {
                            let place = try self.decoder.decode(Feature.self, from: itemobj.rawData())
                            self.searchedPlaces.add(place)
                            self.tableView.reloadData()
                        } catch let error  {
                            if let error = error as? DecodingError {
                                print(error.errorDescription)
                            }
                        }
                    }
                }
            }

            if dataResponse.result.isFailure {
                let error : Error = dataResponse.result.error!
            }

            })

    }

Upvotes: 2

Views: 7604

Answers (1)

denis_lor
denis_lor

Reputation: 6547

For isSuccess(1), isFailure(3) you can actually switch on the response.result. For the value(2) from the response result, you can find it under response.value and last, but not least, the error(4) is available in the switch, check this sample code below that highlights all the relevant info to make your code work:

AF.request(urlStr, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil)
            .responseJSON(completionHandler: { response in
                switch response.result {
                case .success:
                    let resJSON = JSON(response.value)
                    ...
                case .failure(let error):
                    print(error)
                }
            })

Upvotes: 3

Related Questions