簡體   English   中英

如何在 Swift 中將 NSHTTPURLResponse 轉換為字符串

[英]How to convert NSHTTPURLResponse to String in Swift

我想將我的響應從 NSHTTPURLResponse 類型轉換為字符串:

let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) -> Void in 
     println("Response: \(response)")
     var responseText: String = String(data: response, encoding: NSUTF8StringEncoding)
})

下面的行將響應消息輸出到控制台。

println("Response: \(response)")

但是這一行給我帶來了一個錯誤:調用中的額外參數“編碼”。

var responseText: String = String(data: response, encoding: NSUTF8StringEncoding)

如何成功將此“響應”轉換為字符串?

身體

如果需要,獲取數據並使其成為 utf 字符串。 響應的描述不是響應正文

let responseData = String(data: data, encoding: NSUTF8StringEncoding)

頭域

如果你想要一個標題字段:

let httpResponse = response as NSHTTPURLResponse
let field = httpResponse.allHeaderFields["NAME_OF_FIELD"]

更新答案:

事實證明,您想要獲取標題字段的內容。

if let httpResponse = response as? NSHTTPURLResponse {
    if let sessionID = httpResponse.allHeaderFields["JSESSIONID"] as? String {
        // use sessionID
    }
}

當你打印一個對象時,它的description方法被調用。

這就是為什么當你println()它你會得到一個文本表示。

有兩種方法可以實現你想要的。

  1. 簡單的方法

    let responseText = response.description

但是,這僅適用於調試。

  1. 本地化方式

    let localizedResponse = NSHTTPURLResponse.localizedStringForStatusCode(response.statusCode)

每當您需要向用戶顯示錯誤時,請使用第二種方法。

您將需要以下代碼,因為來自您的數據任務的響應數據存儲在data response是 http 響應,帶有狀態代碼等,有關 http 響應的更多信息,請轉到此處

var responseString: String = String(data: data, encoding: NSUTF8StringEncoding)

對於 swift 的更新版本

   let task = session.dataTask(with: url) {(data, response, error) in

        let httpResponse = response as! HTTPURLResponse

        let type = httpResponse.allHeaderFields["Content-Type"]
        print("Content-Type", type)

        let l = httpResponse.allHeaderFields["Content-Length"]
        print("Content-Length", l)

        if let response = response {   // Complete response
            print(response)
        }


            }catch {
                print(error)
            }
        }
        }.resume()

}

如果您想在 Swift 5 中將答案 json 視為字符串

let httpResponse = response as? HTTPURLResponse

if let jsonResponse = String(data: data!, encoding: String.Encoding.utf8) {
    print("JSON String: \(jsonResponse)")
}

它就像var responseText: String = response.description一樣簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM