Migrate JSON request from android to Swift

Asked

Viewed 119 times

0

I’m having a problem migrating a code from an android app to a code in Swift.

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

I am unable to run Swift 2 on Xcode 7 for iOS 9.

Follow the java code 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;
        }
  • What have you tried so far? If you already have some code, even if it is not working, post so it is easier to help you.

  • I made a new post with the code I’m trying

3 answers

0

I recently did a login authentication with Swift’s POST. 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 divide the responsibility of the call, but this code worked with me, I hope it helps you.

  • The lines: Let dataString:Nsdata = data.dataUsingEncoding(Nsutf8stringencoding)! print(data.stringByReplacingOccurrencesOfString("'", withString: """)) Are you experiencing the following error: Value of type 'Nsdata? ' has no Member 'dataUsingEncoding'

0

I am calling the function as follows:

func validatorLogin(){ Let Muser:Nsstring = txtUsuario.text! Let mPassword:Nsstring = txtSena.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 errors?

0


Try something like that:

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 variable dataString, as it seems you only expect a return HTTP 200 or different, just proceed with your logic from the statusCode.

Browser other questions tagged

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