ios - URLSession 函数类似于Alamofire 的responseString?

标签 ios swift nsurlsession

因为我使用的是 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/

相关文章:

ios - 使用 Swift 返回具有自定义数据类型的 JSON 数据时遇到问题

ios - 关于在 Swift 中采用 Objective-C 协议(protocol)的困惑

azure - Xamarin 的 WindowsAzure.Storage 库是否使用 NSUrlSession 进行文件上传?

iOS:谷歌地图 API - markerInfoWindow 与 markerInfoContents

ios - 永远不会调用 NSString 与 UITextField 文本的比较

ios - 从多维 NSDictionary 的子字典值创建排序数组

ios - 如何像 iOS 键盘一样显示和隐藏 UIPickerView?

ios - Swift 3.0 - 用手指在 imageView 上绘图

ios - 来自 NSURLSession 的 performSegueWithIdentifier

ios - NSURLSessionDownloadTask移动临时文件