2015-03-31 113 views
2

我可以在swift中与此代码片段同步连接到服务器。如何在Swift中创建GET,POST和PUT请求?

let URL: NSURL = NSURL(string: "http://someserver.com)! 
let InfoJSON: NSData? = NSData(contentsOfURL: URL) 
let JsonInfo: NSString = NSString(data:InfoJSON!, encoding: NSUTF8StringEncoding)! 
let GameListAttributions: NSArray = NSJSONSerialization.JSONObjectWithData(InfoJSON!, options: .allZeros, error: nil)! as NSArray 

这只适用于一次接收所有信息,但是如何在Swift中使用GET,POST和PUT。无论我搜索多少,我都找不到一个很好的教程或例子来说明如何执行这些。

回答

1

您可以使用swift NSMutableURLRequest来发出POST请求。

斯威夫特GET例:

let requestURL = NSURL(string:"urlhere")! 

var request = NSMutableURLRequest(URL: requestURL) 
request.HTTPMethod = "GET" 

let session = NSURLSession.sharedSession() 
let task = session.dataTaskWithRequest(request, completionHandler:loadedData) 
task.resume() 

文档POST例子:

NSString *bodyData = @"name=Jane+Doe&address=123+Main+St"; 

NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com"]]; 

// Set the request's content type to application/x-www-form-urlencoded 
[postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 

// Designate the request a POST request and specify its body data 
[postRequest setHTTPMethod:@"POST"]; 
[postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]]; 

这是在Objective-C,但很容易转换为迅速。

文档: https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-SW4

4

我创建了一个功能一个项目,以正确的参数,你可以POST,PUT和获得

private func fetchData(feed:String,token:String? = nil,parameters:[String:AnyObject]? = nil,method:String? = nil, onCompletion:(success:Bool,data:NSDictionary?)->Void){ 

    dispatch_async(dispatch_get_main_queue()) { 
     UIApplication.sharedApplication().networkActivityIndicatorVisible = true 

     let url = NSURL(string: feed) 
     if let unwrapped_url = NSURL(string: feed){ 

      let request = NSMutableURLRequest(URL: unwrapped_url) 

      if let tk = token { 
       let authValue = "Token \(tk)" 
       request.setValue(authValue, forHTTPHeaderField: "Authorization") 
      } 

      if let parm = parameters{ 
       if let data = NSJSONSerialization.dataWithJSONObject(parm, options:NSJSONWritingOptions(0), error:nil) as NSData? { 

        //println(NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil)) 
        request.HTTPBody = data 
        request.setValue("application/json", forHTTPHeaderField: "Content-Type") 
        request.setValue("\(data.length)", forHTTPHeaderField: "Content-Length") 
       } 
      } 

      if let unwrapped_method = method { 
       request.HTTPMethod = unwrapped_method 
      } 

      let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() 
      sessionConfiguration.timeoutIntervalForRequest = 15.0 
      let session = NSURLSession(configuration: sessionConfiguration) 
      let taskGetCategories = session.dataTaskWithRequest(request){ (responseData, response, error) -> Void in 



       let statusCode = (response as NSHTTPURLResponse?)?.statusCode 
       //println("Status Code: \(statusCode), error: \(error)") 
       if error != nil || (statusCode != 200 && statusCode != 201 && statusCode != 202){ 
        onCompletion(success: false, data:nil) 

       } 
       else { 
        var e: NSError? 
        if let dictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: .MutableContainers | .AllowFragments, error: &e) as? NSDictionary{ 
         onCompletion(success:true,data:dictionary) 

        } 
        else{ 
         onCompletion(success: false, data:nil) 
        } 
       } 
      } 

      UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
      taskGetCategories.resume() 
     } 
    } 
} 

该如何使用功能:

fetchData(feed,token: Constants.token(), parameters: params, method: "POST", onCompletion: { (success, data) -> Void in 
      if success { //Code after completion} }) 
  • feed - >这是到服务器的链接
  • 令牌(可选) - >某些请求需要令牌用于安全目的
  • 参数(可选) - >这些是您可以传递给服务器的所有参数。 (这是一个词典btw)
  • 方法(可选) - >在这里你可以选择你想要的请求类型(“GET”,“POST”,“PUT”)
  • 完成关闭 - >当请求完成时即将执行的函数。在闭包中,你会得到两个参数:“成功”是一个bool,它表示请求是否成功并显示“数据”。这是一个包含所有响应数据的字典(可能为零)

希望我帮了忙。对不起,我的英语

4
let url = NSURL(string: "https://yourUrl.com") //Remember to put ATS exception if the URL is not https 
let request = NSMutableURLRequest(URL: url!) 
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") //Optional 
request.HTTPMethod = "PUT" 
let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil) 
let data = "[email protected]&password=password".dataUsingEncoding(NSUTF8StringEncoding) 
request.HTTPBody = data 

let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in 

    if error != nil { 

     //handle error 
    } 
    else { 

     let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding) 
     print("Parsed JSON: '\(jsonStr)'") 
    } 
} 
dataTask.resume()