// // ViewController.swift // apirequest // // Created by Andre Cardoso on 9/24/15. // import UIKit import Foundation class ViewController: UIViewController { @IBOutlet weak var phone: UITextField! @IBOutlet weak var email: UITextField! @IBAction func obterLista() { // Exemplo de GET // Setando a URL let endpoint = NSURL(string: "http://0.0.0.0/api/v1/listar-algo") // Obtendo o retorno da URL let data = NSData(contentsOfURL: endpoint!) // Processando o retorno JSON if let json: NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary { // Obtendo a resposta dentro de "content" (ou outra chave que o server retorne) como um array if let items = json["content"] as? NSArray { // Loop dos itens for item in items { let title: AnyObject! = item["title"] let id: AnyObject! = item["id"] let elemento = "ID: \(id) Nome: \(title) \r\n" print(elemento) } } } // Exemplo de GET } @IBAction func enviarDados() { // Callback para atualização da UITextView let atualizaUITextView = {(textString: String) in dispatch_sync(dispatch_get_main_queue()) { self.textViewLojas.text = textString } } // Obtendo os valores digitados let phone: AnyObject! = self.phone.text let email: AnyObject! = self.email.text let deviceId = UIDevice.currentDevice().identifierForVendor!.UUIDString // print(phone) // print(email) // print(deviceId) // Setando a URL let request = NSMutableURLRequest(URL: NSURL(string: "http://0.0.0.0/api/v1/url-de-post")!) // Informando que o método de requisição é POST request.HTTPMethod = "POST" // Setando os dados do post let postString = "phone=\(phone)&deviceId=\(deviceId)&email=\(email)" request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) // Iniciando a chamada à API let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if error != nil { print("error=\(error)") return } //print("response = \(response)") var respostaPost = "" // Processando o retorno JSON if let json: NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary { let dados = json["content"] let token: String! = dados?["token"] as! String respostaPost += "Token: \(token) \r\n" atualizaUITextView(respostaPost) } } // realizando a requisição task.resume() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }