[Solved] How would you handle getting new data from the server? [closed]


You might feel surprised to have received so many vote-downs. The reason is that you have not provided any information concerning what you have tried to solve the problem.

Since you have not provided any specifics either, I’ll assume you want some basically structured data (e.g. JSON) to send/retrieve from server.

Following code will let you send GET/POST/PUT requests and handle it easily.

  public enum RESTMethod:String {
       case get = "GET"
       case post = "POST"
       case put = "PUT"
  }

  public func sendRequest(_ url: String,
                        method: RESTMethod,
                        headers: [String : String],
                        parameters: [String : Any],
                        completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionTask! {
    let requestURL: URL
    if method == .get {
        let parameterString = parameters.stringFromHttpParameters()
        requestURL = URL(string:"\(url)?\(parameterString)")!
    } else {
        requestURL = URL(string: url)!
    }


    var request = URLRequest(url: requestURL)
    request.allHTTPHeaderFields = headers
    request.httpMethod = method.rawValue
    if method == .post {
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
        request.httpBody = jsonData
    }
    request.timeoutInterval = 60


    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

        completionHandler(data,response,error)
    }

    task.resume()

    return task

}


extension Dictionary {

/// Build string representation of HTTP parameter dictionary of keys and objects

func stringFromHttpParameters() -> String {
    let parameterArray = self.map { (key, value) -> String in
        let percentEscapedKey = (key as! String).addingPercentEncodingForURLQueryValue()!
        let percentEscapedValue = (value as? String ?? "\(value)").addingPercentEncodingForURLQueryValue()!
        return "\(percentEscapedKey)=\(percentEscapedValue)"
    }

    return parameterArray.joined(separator: "&")
}

}

Usage:

sendRequest("http://yourserver",
             method: .get, // .post or .put
             headers: [],
             parameters: [],
             completionHandler: { (data, response, error) in

   // Handle response here

})

0

solved How would you handle getting new data from the server? [closed]