2015-03-31 118 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()