2014-12-26 2 views
4

나는 IOS 개발에 새로운 그리고 난 신속한 언어로 시작을 사용하여 서버에 JSON 데이터를 전송합니다. 어떻게 생성하고 신속한 언어

나는 두 개의 텍스트 필드의 값을 얻을 JSON으로 두 텍스트 필드를 변환하고 서버 receive.php에 그 JSON을 보내려고 해요.

텍스트 필드가 되는 견인 재질 - 구글 번역 참고 할 수 있습니다 - 내가 버튼을 클릭 할 때 JSON & 서버에 그것을 보낼 만들려면 어떻게해야합니까

을 통과 - 이름? NSURLSession로 HTTP POST 메서드를 사용하여

+0

중복 가능성 [스위프트에서 HTTP 요청을하는 방법?] (http://stackoverflow.com에있는 SubmitAction 메소드를 호출하는 가정 해 봅시다/questions/24016142/how-to-make-an-http-request-in-swift) – Rudy

+1

하지만 Json을 생성하고 보내는 방법은 없습니다. – Uday

답변

18

. 의 당신이

스위프트 로그인 버튼을 눌러 3

@IBAction func submitAction(sender: AnyObject) { 

    //declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid 

    let parameters = ["name": nametextField.text, "password": passwordTextField.text] as Dictionary<String, String> 

    //create the url with URL 
    let url = URL(string: "http://myServerName.com/api")! //change the url 

    //create the session object 
    let session = URLSession.shared 

    //now create the URLRequest object using the url object 
    var request = URLRequest(url: url) 
    request.httpMethod = "POST" //set http method as POST 

    do { 
     request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body 

    } catch let error { 
     print(error.localizedDescription) 
    } 

    request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
    request.addValue("application/json", forHTTPHeaderField: "Accept") 

    //create dataTask using the session object to send data to the server 
    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in 

     guard error == nil else { 
      return 
     } 

     guard let data = data else { 
      return 
     } 

     do { 
      //create json object from data 
      if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] { 
       print(json) 
       // handle json... 
      } 

     } catch let error { 
      print(error.localizedDescription) 
     } 
    }) 
    task.resume() 
} 
+0

답변에 무엇이 잘못 되었습니까? – suhit

+0

당신이 코드를 통해 이동하는 경우, 그것은 자기 설명이다, 나는 코드 – suhit

+0

내부에서 무슨 일이 진행되고 있는지 설명하는 내 대답을 편집하고 난 :) 훨씬 더 잘 대답 – suhit

관련 문제