*Alamofire version: 4.4.0
*Xcode version: 8.3.2
*Swift version: Apple Swift version 3.1 (swiftlang-802.0.53 clang-802.0.42)
*Platform(s) running Alamofire: Any simulator (xcode 8.3.2)
Hi, could someone give me a hand figuring this one out. Thanks.
I am doing two different html requests with Alamofire, both work fine using a browser and return the same html source, however using Alamofire one of them fails to decode the data response to string.
Notice the small difference in the urls is the second url has an 'n' at the end
let urlString1 = "http://www.dictionary.com/browse/andalusia"
let urlString2 = "http://www.dictionary.com/browse/andalusian"
Alamofire.request(urlString<1 or 2>).responseString { (response) in
switch response.result {
case .success(let value):
// Do something with html string
case .failure(let error):
print(error)
}
}
Results:
Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.stringSerializationFailed(Unicode (UTF-8)))
Like the error description says, Alamofire couldn't parse the string as UTF-8 (despite that being what dictionary.com
returns by default). You should investigate whether their response is actually a valid UTF-8 string. If the site can't be counted on to return a proper type, then you may want to write your own string parser that can fallback to other encodings.
@ghost I encounter the same problem
I solved by using .responseData
& String(decoding:as:)
Alamofire.request(...).responseData { response in
guard let data = response.data else { return }
let utf8Text = String(data: data, encoding: .utf8) ?? String(decoding: data, as: UTF8.self)
}
Noted that String(data:encoding:) is faster then String(decoding:as:)
@gaplo917
thank you saved my day ;-)
Most helpful comment
@ghost I encounter the same problem
I solved by using
.responseData
&String(decoding:as:)
Noted that String(data:encoding:) is faster then String(decoding:as:)
Ref:
https://bugs.swift.org/browse/SR-6261