因为我使用的是 cocoapods 并且有必要的 Objective-C 依赖项,所以我不能使用框架,因此不能使用 Alamofire...Alamofire 有一个函数 responseString(见下面的代码),所以我需要使用 URLSession 在本地执行此操作,我怎样才能做到这一点?
Alamofire.request(testURL).responseString { response in
print("\(response.result.isSuccess)")
if let html = response.result.value {
parseHTML(html: html)
}
}
Alamofire:
extension DataRequest {
/// Creates a response serializer that returns a result string type initialized from the response data with
/// the specified string encoding.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
/// response, falling back to the default HTTP default character set, ISO-8859-1.
///
/// - returns: A string response serializer.
public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer<String> {
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error)
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
/// server response, falling back to the default HTTP default character set,
/// ISO-8859-1.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseString(
queue: DispatchQueue? = nil,
encoding: String.Encoding? = nil,
completionHandler: @escaping (DataResponse<String>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
最佳答案
获取的基本代码success
和 value / html
来自 URLSessionDataTask
的值是
dataTask(url: url) { (data, response, error) in
guard error == nil else {
print(error!)
// handle error
return
}
let success : Bool
let html : String
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
success = true
html = String(data:data!, encoding: .utf8)! // or .isoLatin1
} else {
success = false
print("http response error")
html = ""
}
print(html, success)
}
它采用标准文本编码 (utf8)。和 URLRequest
只需要 POST
请求。
关于ios - URLSession 函数类似于Alamofire 的responseString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44119062/