URLSession函数类似于Alamofire的responseString?

时间:2017-05-22 17:46:09

标签: 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
        )
    }
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

从您的回复中获取数据,将其转换为字符串。 Alamofire在这方面做得不多。

right()