GarySabo GarySabo - 1 year ago 37
iOS Question

URLSession function similar to Alamofire's responseString?

Because I am using cocoapods and have necessary Objective-C dependencies, I cannot use frameworks and as such cannot use Alamofire... Alamofire has a function responseString (see code below), so I need to do this natively using URLSession, how can I do this?

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

Answer Source

The essential code to get the success and value / html values from URLSessionDataTask is

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

It assumes the standard text encoding (utf8). And URLRequest is only needed for a POST request.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download