2017-01-25 113 views
-3

我有node.js服務器,您可以在這裏查看:https://github.com/achompolov/srv-EatHealthy/blob/api-v1/server.js。服務器連接到MongoDB,客戶端/服務器使用socket.io連接nodejs和swift。我需要創建新的用戶,只要點擊註冊按鈕,但我不知道如何在swift中獲得POST/GET方法,並將它們發送到服務器以在數據庫中創建用戶。下面是註冊按鈕的swift3代碼:Node.js&Swift3 REST API

/* Send the sign up form to the server */ 
@IBAction func signUpButtonClicked(_ sender: Any) { 
    SocketIOManager.sharedInstance.socket.emit("signUpClicked", [signUpNameTextField.text!, 
                   signUpEmailTextField.text!, 
                   signUpUsernameTextField.text!, 
                   signUpPasswordTextField.text!, 
                   signUpBirthDate.text!, 
                   signUpGender.text!]) 
} 

我一直在使用這個

var request = URLRequest(url: URL(string: "http://localhost:8080/api/users")!) 
    request.httpMethod = "POST" 

嘗試,但我不知道以後的事情。 我已經在服務器端創建post/get方法,並且通過使用Postman,我可以發佈/刪除/獲取/放入MongoDB。我會感激的幫助。 下面是來自Postman和MongoDB Compass的圖片,以確保它在服務器端工作。

Postman with some test users created

MongoDB Compass with the test users created

+0

的可能的複製[HTTP斯威夫特3請求(http://stackoverflow.com/questions/38292793/http-requests-in-swift-3) – muescha

+0

你谷歌對於https://www.google.com/search?q=URLRequest+post+swift+3? – muescha

+0

外觀還適用於[Alamofire](https://github.com/Alamofire/Alamofire)(也許還有[Moya](https://github.com/Moya/Moya)) – muescha

回答

0

生斯威夫特

如果您正在尋找斯威夫特HTTP POST請求的最簡單,原始的版本,你可以試試這個:

1 )。通過標題,端點和方法類型構建您的請求(POST)。在這裏,我假設你正在使用application/json編碼。

var request = URLRequest(url: URL(string: "https://yoursite.endpoint.com/")!) 
    request.httpMethod = "POST" 
    request.addValue("application/json", forHTTPHeaderField: "Content-Type") 

//And if you need an Auth Key, add this line 
    request.addValue("key=someAuthkey", forHTTPHeaderField: "Authorization") 

2)。準備你的JSON。

let RequestDetailsDictionary = [ 
    { 
    "id": "ObjectID('09374091375409984029')", 
    "name": "testUser",  
    "__v": 0 
    } 
] 

4)。附上您的要求在dotrycatch

let err = NSError() 

do{ 
    request.httpBody = try JSONSerialization.data(withJSONObject: RequestDetailsDictionary, options: []) 
}catch{ 
    print("ERROR: \(err)") 
} 

URLSession.shared.dataTask(with: request, completionHandler: { 
    (data, response, error) in 
    if(error != nil){ 
     print("ERROR: \(error)") 
    }else{ 
     do{ 
      let resp = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject] 
      print("RESPONSE: \(resp)") 

     }catch let error as NSError{ 
      print("ERROR: \(error)") 
     } 
    } 
}).resume() 

Alamofire

建議,以及更簡單的方法,將安裝Alamofire,然後做這樣的事情。請注意,這是使用x-www-form-urlencoded

var headers: HTTPHeaders = [ 
    "Content-Type": "application/x-www-form-urlencoded" 
] 

let parameters: Parameters = [ 
    "id": "\(number)", 
    "name": "ObjectID(908227c74d576fa7c)", 
    "__v": 0 
] 

let urlString = "https://yoursite.endpoint.com/" 
var URLs: URL? 
do{ 
    URL = try urlString.asURL() 

}catch{ 
    print("ERROR: \(AFError.self)") 
} 

Alamofire.request(URL!, method: .post, parameters: parameters, encoding: URLEncoding(destination: .httpBody), headers: headers).response{ response in 

    if response.error != nil{ 
     print(response.error!) 
     return 
    } 

    //do something HERE with your successful request 

    }