2017-08-27 70 views

回答

0

您可能會因爲收到如此多的投票而感到驚訝。原因是你沒有提供任何有關what you have tried to solve the problem的信息。

既然你還沒有提供任何細節,我假設你想要一些基本結構化的數據(例如JSON)從服務器發送/檢索。

以下代碼可讓您發送GET/POST/PUT請求並輕鬆處理。

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: "&") 
} 

} 

用法:

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

    // Handle response here 

})