Handling XML data with Alamofire in Swift

后端 未结 7 1994
一向
一向 2020-12-24 02:57

I started to use cocoapods with my current ios project. I need to use SOAP to get content with easy way for my ios project. I have googled it and Alamofire pod is great for

7条回答
  •  无人及你
    2020-12-24 03:29

    Alamofire 4.x - Swift 3.x:

    (please note that in this example I've used URLEncoding.default instead of URLEncoding.xml because the xml parameter exclude the possibility to pass parameters and headers, so default is more confortable.)

    let url = "https://httpbin.org/get"
    let parameters: Parameters = ["foo": "bar"]
    let headers: HTTPHeaders = [
        "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
        "Accept": "application/json"
    ]
    Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers)
    .responseString { response in
        print(" - API url: \(String(describing: response.request!))")   // original url request
        var statusCode = response.response?.statusCode
    
        switch response.result {
        case .success:
            print("status code is: \(String(describing: statusCode))")
            if let string = response.result.value {
                print("XML: \(string)")
            }
        case .failure(let error):
            statusCode = error._code // statusCode private
            print("status code is: \(String(describing: statusCode))")
            print(error)
        }
    }
    

    Alamofire 3.0 october 2015 and Xcode 7 according to the 3.0.0-beta.3 README and the Alamofire 3.0 Migration Guide.

    For me the correct syntax is:

    Alamofire.request(.GET, url, parameters: params, encoding: ParameterEncoding.URL).responsePropertyList { response in
    
                if let error = response.result.error {
                    print("Error: \(error)")
    
                    // parsing the data to an array
                } else if let array = response.result.value as? [[String: String]] {
    
                    if array.isEmpty {
                        print("No data")
    
                    } else { 
                        //Do whatever you want to do with the array here
                    }
                }
            }
    

    If you want a good XML parser, please take a look to SWXMLHash.

    An example could be: let xml = SWXMLHash.parse(string)

提交回复
热议问题