Migrate JSON request from android to swift

0

I'm having a problem migrating code from an android app to swift code.

This code is responsible for authenticating the user and password of an application.

I can not do swift 2 on xcode 7 for iOS 9.

Follow the code in java below:

@Override
        protected Boolean doInBackground(Void... params) {
            ArrayList<NameValuePair> postParameters;
            postParameters = new ArrayList<>();
            postParameters.add(new BasicNameValuePair("login", mUser));
            postParameters.add(new BasicNameValuePair("password", mPassword));

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(sUrl);

            HttpResponse httpResponse;

            try {
                String base64 = Base64.encodeToString((mUser + ":" + mPassword).getBytes(),
                        Base64.NO_WRAP);
                httpPost.addHeader("Authorization", "Basic " + base64);
                httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
                httpResponse = httpclient.execute(httpPost);
            } catch (IOException e) {
                Log.e(TAG, "Error on request login", e);
                return false;
            }

            int responseCode = httpResponse.getStatusLine().getStatusCode();

            return responseCode == 200;
        }
    
asked by anonymous 16.11.2015 / 03:53

3 answers

0

Try something like this:

let userPasswordString = "\(mUser):\(mPassword)"
let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions([])

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = ["Authorization" : "Basic \(base64EncodedCredential)"]

let session = NSURLSession(configuration: config)
let url = NSURL(string: sUrl)
let request = NSMutableURLRequest(URL: url!, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 30.0)

let post = "login=\(mUser)&password=\(mPassword)"

request.HTTPMethod = "POST"
request.HTTPBody = post.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)

let task = session.dataTaskWithRequest(request) {(data, response, error) in
    if let httpResponse: NSURLResponse = response {
        if let statusCode: Int = (httpResponse as! NSHTTPURLResponse).statusCode {
            if statusCode == 200 {
                let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print(dataString)
            }
        }
    }
}

task.resume()

Your answer is in the dataString variable, as it looks like you only expect a HTTP 200 return or different, just proceed with your logic from statusCode . >     

16.11.2015 / 11:37
0

I recently did a login authentication with POST in swift. I used the code below:

  let URL = NSURL(string:  "http://linkdoseuservidor")

  let mutableURLRequest = NSMutableURLRequest(URL: URL!)

  mutableURLRequest.HTTPMethod = "POST"

  let parameters = ["email":"[email protected]", "senha":"2345"]

  do {

        mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()

        let session = NSURLSession(configuration: config)

        let task = session.dataTaskWithRequest(mutableURLRequest, completionHandler: {

            (data, response, error) in

            guard let responseData = data else {

                print("Error: did not receive data")

                return
            }

            guard error == nil else {

                print("error calling POST on /posts/1")

                print(error)

                return
            }  

            let post: NSDictionary

            do {

                post = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as! NSDictionary
            }

            catch {

                print("error parsing response from POST on /posts")

                return
            }

            print("resultado: ")

            print(post)

            let dataJSON = post["data"] as! NSDictionary

            print(dataJSON)

            print(post["status"])

            let dataString:NSData = data.dataUsingEncoding(NSUTF8StringEncoding)!

            print(data.stringByReplacingOccurrencesOfString("\'", withString: "\""))

            do{

                let dataJSON:NSDictionary = try NSJSONSerialization.JSONObjectWithData(dataString, options: []) as! NSDictionary

                let idUsuario = dataJSON["id"]

                let nomeUsuario = dataJSON["nome"]

                print(idUsuario)

                print(nomeUsuario)

            }

            catch let e as NSError{

                print (e)

                print("error data string json")

            }

        })

        task.resume()

    }

    catch {

        print("error parsing response from POST on /posts")

        return
    }

But it is advisable to divide responsibilities, use classes like service and controllers to share the responsibility of the call, but this code worked for me, I hope it helps.

    
16.11.2015 / 21:26
0

I'm calling the function as follows:

func validaLogin () {         let mUser: NSString = txtUsuario.text!         let mPassword: NSString = txtSenha.text!

    let userPasswordString = "\(mUser):\(mPassword)"
    let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
    let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions([])

    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    config.HTTPAdditionalHeaders = ["Authorization" : "Basic \(base64EncodedCredential)"]

    let session = NSURLSession(configuration: config)
    let url = NSURL(string: "http:minhaURL")
    let request = NSMutableURLRequest(URL: url!, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 30.0)

    let post = "login=\(mUser)&password=\(mPassword)"
    NSLog("post %@", post);

    request.HTTPMethod = "POST"
    request.HTTPBody = post.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)

    let task = session.dataTaskWithRequest(request) {(data, response, error) in
        if let httpResponse: NSURLResponse = response {
            if let statusCode: Int = (httpResponse as! NSHTTPURLResponse).statusCode {
                if statusCode == 200 {
                    let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                    NSLog("dataString %@", dataString!)
                }
            }
        }
    }
    task.resume();
}

How do I validate my errors?

    
17.11.2015 / 02:19