Post request on webservice with Swift

Asked

Viewed 690 times

1

I’m starting now to use the still, I managed to make requests . get but stopped in post request.

I created a user class that has name, email and password, however I can’t post a user 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 faltering 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'

Could someone tell me if this is the right way to do a post? How to pass the object to json in the right way?

  • Swift 2 or Swift 3? I don’t know how you do using Alamofire, if you want I can show how you do a post json using Urlrequest and Urlsession (Swift 3) or Nsurlsession (Swift 2).

  • Swift 2, every solution is life well ;)

  • Kleiton speaks from a look at the answer any doubt tells me. If you need help to convert string back to image also just talk. abs

  • Thank you Leo Dabus, was of great help your solution. Hugs

  • You’re welcome Kleiton. Abs

1 answer

0


Don’t rely 100% on syntax because I wrote it directly in the browser and I’ve only been programmed using Swift 3. It should be enough to give you an idea of what Swift needs, but it’s not a task for beginners. You must do it this way:

// 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)
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.