Request Post in webservice with swift

1

I'm now starting to use alamofire, I was able to quietly make requests .get however I crashed the post request.

I created a user class that has name, email and password, however I can not post a user stay object

let usuario = Usuario()
    usuario.nome = "Kleiton"
    usuario.senha = "1234"
    usuario.email = "[email protected]"

    do{
        let usuarioJson = try NSJSONSerialization.dataWithJSONObject(usuario, options: NSJSONWritingOptions())

        Alamofire.request(.POST, "ws/inserir", parameters: usuarioJson as AnyObject as? [String : AnyObject]).responseJSON(completionHandler: { (response) in
            print(response.result)
        })
    }catch{

    }

I may be wavering somewhere, I tried to pass the object to json let usuarioJson = try NSJSONSerialization.dataWithJSONObject(usuario, options: NSJSONWritingOptions()) but I get the following error

  

uncaught exception 'NSInvalidArgumentException', reason: '***   + [NSJSONSerialization dataWithJSONObject: options: error:]: Invalid top-level type in JSON write '

Can anyone tell me if this is the correct way to do a post? How to pass the object to json in the correct way?

    
asked by anonymous 02.08.2016 / 23:49

1 answer

0

Do not rely 100% on syntax because I wrote directly in the browser and I only have it programmed using Swift 3. It should be enough for you to have an idea of what you need, but it's not a beginner's task. You should do this:

// Primeiro crie uma variável com o link para POST do seu servidor. 
let postLink = "https://www.seudominio.com/restapi/usuario/save"

// criar a URL a partir do link
if let postURL = NSURL(string: postLink) { 

    let urlRequest = NSURLMutableRequest(url: postURL) 

    // variáveis que vão preencher o seu dicionário json
    let nome = "Kleiton"
    let sobrenome = "Batista"
    let email = "[email protected]"
    var photoString = ""

    // não sei como funciona a sua API mas normalmente se envia uma imagem usando Base64 String Encoding
    // profileImage é uma UIImage opcional (UIImage?)
    if let myPictureData = profileImage?.jpegData(1.0),
        let myPictureBase64String = myPictureData.base64EncodedString {
        photoString = myPictureBase64String
        print("photoOK")
    }
    // crie o seu dicionário json para post
    let userJSON = [
            "email"         : email,
            "nome"          : nome,
            "sobrenome"     : sobrenome,
            "foto"          : photoString]
    // voce precisa usar NSJSONSerialization.dataWithJSONObject

    do {
        let jsonData = try NSJSONSerialization.dataWithJSONObject( userJSON, options: .prettyPrinted)
        urlRequest.httpMethod = "POST"
        urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        urlRequest.httpBody = jsonData
        // use  data task with request para mandar os dados async    
        NSURLSession.sharedSession().dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) in
            guard
                let httpURLResponse = response as? HTTPURLResponse , httpURLResponse.statusCode == 200,
                let data = data where error == nil
            else {
                print(error?.localizedDescription)
                return
            }
            print("NEW USER OK")
            // checkando o retorno da API
            do {
                let result = try NSJSONSerialization.JSONObjectWithData( data, options: []) as? [String:AnyObject]
                print("Result:", result)
            } catch let error as NSError {
                print("JSONSerialization Error:", error.localizedDescription)
            }
        }).resume()
    } catch let error as NSError {
           print("NSJSONSerialization\nError:\n", error.localizedDescription)
    }
}

extension UIImage {
    func jpegData(quality: CGFloat) -> Data? {
        return UIImageJPEGRepresentation(self, quality)
    }
}

extension NSData {
    var base64EncodedString: String? {
        return base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
    }
}
    
04.08.2016 / 06:58