Alamofire: request.responseString - stringSerializationFailed(์œ ๋‹ˆ์ฝ”๋“œ(UTF-8))

์— ๋งŒ๋“  2017๋…„ 12์›” 26์ผ  ยท  3์ฝ”๋ฉ˜ํŠธ  ยท  ์ถœ์ฒ˜: Alamofire/Alamofire

*Alamofire ๋ฒ„์ „: 4.4.0* Xcode ๋ฒ„์ „: 8.3.2
*Swift ๋ฒ„์ „: Apple Swift ๋ฒ„์ „ 3.1(swiftlang-802.0.53 clang-802.0.42)* Alamofire๋ฅผ ์‹คํ–‰ํ•˜๋Š” ํ”Œ๋žซํผ: ๋ชจ๋“  ์‹œ๋ฎฌ๋ ˆ์ดํ„ฐ(xcode 8.3.2)

์•ˆ๋…•ํ•˜์„ธ์š”, ๋ˆ„๊ตฐ๊ฐ€ ๋‚˜์—๊ฒŒ ์ด๊ฒƒ์„ ์•Œ์•„๋‚ด๋Š” ๋ฐ ๋„์›€์„ ์ค„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๊นŒ? ๊ฐ์‚ฌ ํ•ด์š”.

Alamofire๋กœ ๋‘ ๊ฐ€์ง€ ๋‹ค๋ฅธ html ์š”์ฒญ์„ ์ˆ˜ํ–‰ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๋‘˜ ๋‹ค ๋ธŒ๋ผ์šฐ์ €๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ œ๋Œ€๋กœ ์ž‘๋™ํ•˜๊ณ  ๋™์ผํ•œ html ์†Œ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•˜์ง€๋งŒ Alamofire๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๊ทธ ์ค‘ ํ•˜๋‚˜๊ฐ€ ๋ฌธ์ž์—ด์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ ์‘๋‹ต์„ ๋””์ฝ”๋”ฉํ•˜์ง€ ๋ชปํ•ฉ๋‹ˆ๋‹ค.
ํ•œ URL์— ์ž‘์€ ์ฐจ์ด๋ฅผ ์ฃผ๋ชฉํ•˜๋Š” ์ œ URL์˜ ๋์— 'N'์„ ๊ฐ–๋Š”๋‹ค

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)
    }
}

๊ฒฐ๊ณผ:

  • urlString1์€ html ๋ฌธ์ž์—ด์„ ์ž˜ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค.
  • urlString2๋Š” ์˜ค๋ฅ˜๋ฅผ ์ธ์‡„ํ•ฉ๋‹ˆ๋‹ค.
    Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.stringSerializationFailed(Unicode (UTF-8)))

๊ฐ€์žฅ ์œ ์šฉํ•œ ๋Œ“๊ธ€

@ghost ๊ฐ™์€ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.

.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)
    }

String(data:encoding:)์ด String(decoding:as:)๋ณด๋‹ค ๋น ๋ฆ…๋‹ˆ๋‹ค.

์ฐธ์กฐ:
https://bugs.swift.org/browse/SR-6261

๋ชจ๋“  3 ๋Œ“๊ธ€

์˜ค๋ฅ˜ ์„ค๋ช…์—์„œ ์•Œ ์ˆ˜ ์žˆ๋“ฏ์ด Alamofire๋Š” ๋ฌธ์ž์—ด์„ UTF-8๋กœ ๊ตฌ๋ฌธ ๋ถ„์„ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค( dictionary.com ๊ฐ€ ๊ธฐ๋ณธ์ ์œผ๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š”

@ghost ๊ฐ™์€ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.

.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)
    }

String(data:encoding:)์ด String(decoding:as:)๋ณด๋‹ค ๋น ๋ฆ…๋‹ˆ๋‹ค.

์ฐธ์กฐ:
https://bugs.swift.org/browse/SR-6261

@gaplo917
๋•๋ถ„์— ํ•˜๋ฃจ๋ฅผ ๊ตฌํ–ˆ์Šต๋‹ˆ๋‹ค ;-)

์ด ํŽ˜์ด์ง€๊ฐ€ ๋„์›€์ด ๋˜์—ˆ๋‚˜์š”?
0 / 5 - 0 ๋“ฑ๊ธ‰