为swift添加POST,PUT,DELETE请求类

时间:2016-04-20 17:30:53

标签: ios swift macos httpwebrequest

我已经创建了一个客户服务类来从web api发出调用GET请求。我尝试扩展但有更多网络方法POSTPUTDelete。我没有找到如何使用swift closure创建POST,PUT,Delete的好例子.I只是想问一下如何将POST,PUT,Delete添加到客户端服务?

import Foundation

class ClientService{

    func getClients(searchstring:String,pageNumber:Int,callBack:(NSArray)->()){
        request("\(_settings.baseUrl)Client/\(searchstring)/\(String(pageNumber))/rrn/brns", callBack: callBack)
    }

    func request(url:String,callBack:(NSArray)->()){
        let nsURL = NSURL(string:url);
        let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!){
            (data,response,error) in
            do {
                let response = try NSJSONSerialization.JSONObjectWithData(data!, options:  NSJSONReadingOptions.MutableContainers) as! NSArray
                callBack(response)
            } catch let error as NSError {
                print("json error: \(error.localizedDescription)")
            }
        }
        task.resume()
    }

    init(){
        self._settings = Settings();
    }

    var _settings:Settings!;
}

4 个答案:

答案 0 :(得分:4)

你走在正确的轨道上。我为get,post,put,delete等创建了一个单独的函数。但如果你愿意,你可以在一个函数中创建它们。

请记住,此代码仅用于说明如何执行此操作。您需要根据需要进行修改。

func request(url:String, method: String, params: [String: String], completion: ([AnyObject])->() ){
    if let nsURL = NSURL(string:url) {
        let request = NSMutableURLRequest(URL: nsURL)
        if method == "POST" {
            // convert key, value pairs into param string
            postString = params.map { "\($0.0)=\($0.1)" }.joinWithSeparator("&")
            request.HTTPMethod = "POST"
            request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)            
        }
        else if method == "GET" {
            postString = params.map { "\($0.0)=\($0.1)" }.joinWithSeparator("&")
            request.HTTPMethod = "GET"
        }
        else if method == "PUT" {
            putString = params.map { "\($0.0)=\($0.1)" }.joinWithSeparator("&")
            request.HTTPMethod = "PUT"
            request.HTTPBody = putString.dataUsingEncoding(NSUTF8StringEncoding)                        
        }
        // Add other verbs here

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            (data, response, error) in
            do {

                // what happens if error is not nil? 
                // That means something went wrong.

                // Make sure there really is some data
                if let data = data {
                    let response = try NSJSONSerialization.JSONObjectWithData(data, options:  NSJSONReadingOptions.MutableContainers) 
                    completion(response)                    
                }
                else {
                    // Data is nil.
                }
            } catch let error as NSError {
                print("json error: \(error.localizedDescription)")
            }
        }
        task.resume()            
    }
    else{
        // Could not make url. Is the url bad?
        // You could call the completion handler (callback) here with some value indicating an error
    }    
}

这样称呼:

request("http://somedomain.etc", "POST", ["key1" : "value1", "key2", "values2"]) { 
    (result) in 
    // Handle result here.
}

你会注意到我消灭了NSArray。 [AnyObject]是Swift的方法。

我建议您在完成处理程序中添加某种错误指示符。这样可以让你发现出现问题并处理它。

使用时要非常谨慎!解开变量。这是应用程序崩溃的最常见原因。

答案 1 :(得分:2)

我用于mes项目Alamofire(Swift中的优雅HTTP网络),我喜欢它

如何使用POST

的示例
let parameters = [
    "foo": "bar",
    "baz": ["a", 1],
    "qux": [
        "x": 1,
        "y": 2,
        "z": 3
    ]
]

Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters)
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3

以及如何使用删除

Alamofire.request(.DELETE, "https://httpbin.org/delete") 

去文档是非常好的 https://github.com/Alamofire/Alamofire 如果你想在没有框架的情况下使用swift

这是如何使用POST的示例

 var request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:4567/login"))
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    var params = ["username":"jameson", "password":"password"] as Dictionary<String, String>

    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        println("Response: \(response)")
        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("Body: \(strData)")
        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(err != nil) {
            println(err!.localizedDescription)
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("Error could not parse JSON: '\(jsonStr)'")
        }
        else {
            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            if let parseJSON = json {
                // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                var success = parseJSON["success"] as? Int
                println("Succes: \(success)")
            }
            else {
                // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("Error could not parse JSON: \(jsonStr)")
            }
        }
    })

    task.resume()

答案 2 :(得分:1)

您可以创建如下的HTTP请求,而不是使用dataTaskWithUrl:     let request = NSMutableURLRequest(URL:url)     request.HTTPMethod =&#34; POST&#34;     request.HTTPBody = jsonData     request.setValue(&#34; application / json&#34;,forHTTPHeaderField:&#34; Content-Type&#34;)     request.setValue(String(jsonData?。length),forHTTPHeaderField:&#34; Content-Length&#34;)     let session = NSURLSession.sharedSession()     let task = session.dataTaskWithRequest(request){data,res,error in       //等等 上面示例中的其他所有内容都是相同的。当然,您必须提供json数据。为此,你可以做这样的事情:     let data:[String:AnyObject] = [&#34; nameValue&#34;:dataValue]     var jsonData:NSData? =没有     做{         jsonData =尝试NSJSONSerialization.dataWithJSONObject(数据,选项:NSJSONWritingOptions(rawValue:0))     } catch {         //一些错误序列化     }

答案 3 :(得分:1)

Swift 4版本(我认为):

func restRequest(url:String, method: String, params: [String: String], completion: @escaping ([AnyObject])->() ){
    if let nsURL = NSURL(string:url) {
        let request = NSMutableURLRequest(url: nsURL as URL)
        if method == "POST" {
            // convert key, value pairs into param string
            let postString = params.map { "\($0.0)=\($0.1)" }.joined(separator: "&")
            request.httpMethod = "POST"
            request.httpBody = postString.data(using: String.Encoding.utf8)
        }
        else if method == "GET" {
            let postString = params.map { "\($0.0)=\($0.1)" }.joined(separator: "&")
            request.httpMethod = "GET"
        }
        else if method == "PUT" {
            let putString = params.map { "\($0.0)=\($0.1)" }.joined(separator: "&")
            request.httpMethod = "PUT"
            request.httpBody = putString.data(using: String.Encoding.utf8)
        }
        // Add other verbs here

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

                // what happens if error is not nil?
                // That means something went wrong.

                // Make sure there really is some data
                if let data = data {
                    let response = try JSONSerialization.JSONObjectWithData(data, options:  JSONSerialization.ReadingOptions.MutableContainers)
                    completion(response)
                }
                else {
                    // Data is nil.
                }
            } catch let error as NSError {
                print("json error: \(error.localizedDescription)")
            }
        }
        task.resume()
    }
    else{
        // Could not make url. Is the url bad?
        // You could call the completion handler (callback) here with some value indicating an error
    }
}