Swift gzipped response

久未见 提交于 2020-01-06 04:46:24

问题


I've serialized a JSON response in my Swift app and the parsed result is a single byte array

{
d =     (
    31,
    139,
    8,
    0,
    0,
    9,
    110,
    136,
    0,
    255,
    236,
    125,

how do I decode this byte array into actual data i can work with?

here is my swift code that fetches and parses the response

`func getWRHPSData(completionHandlerForPOST: @escaping (_ result: AnyObject?, _ error: NSError?) -> Void) -> Void {

    let request = NSMutableURLRequest(url: createURL())
    request.httpMethod = "POST"
    request.addValue("gzip, inflate", forHTTPHeaderField: "Accept")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")

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

        func sendError(_ error: String) {
            print(error)
            let userInfo = [NSLocalizedDescriptionKey : error]
            completionHandlerForPOST(nil, NSError(domain: "taskForGETMethod", code: 1, userInfo: userInfo))
        }

        /* GUARD: Was there an error? */
        guard (error == nil) else {
            sendError("There was an error with your request: \(error!)")
            return
        }

        /* GUARD: Did we get a successful 2XX response? */
        guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
            sendError("Your request returned a status code other than 2xx!")
            return
        }

        /* GUARD: Was there any data returned? */
        guard let data = data else {
            sendError("No data was returned by the request!")
            return
        }



        /* 5/6. Parse the data and use the data (happens in completion handler) */
        self.parseData(data, completionHandlerForConvertData: completionHandlerForPOST)
    }

    /* 7. Start the request */
    task.resume()
}

// given raw JSON, return a usable Foundation object
private func parseData(_ data: Data, completionHandlerForConvertData: (_ result: AnyObject?, _ error: NSError?) -> Void) {

    var parsedResult: AnyObject! = nil
    do {
        parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject
    } catch {
        let userInfo = [NSLocalizedDescriptionKey : "Could not parse the data as JSON: '\(data)'"]
        completionHandlerForConvertData(nil, NSError(domain: "convertDataWithCompletionHandler", code: 1, userInfo: userInfo))
    }

    print(parsedResult)
    completionHandlerForConvertData(parsedResult, nil)
}`

来源:https://stackoverflow.com/questions/44729517/swift-gzipped-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!