Search code examples
javaandroidiosnsurlconnectionandroid-volley

Converting Android Volley Request to iOS NSURL asynchronous request


I have the following method in my Android app which I use for user login/registration.

public void registerUser(final String username, final String email, final String password) {
    pDialog.setMessage("Signing Up...");
    pDialog.show();

    request = new StringRequest(Method.POST, SL_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            pDialog.dismiss();
            String[] split = s.split("Config.php");
            String after = split[1];
            try {
                JSONObject jsonObject = new JSONObject(after);
                boolean error = jsonObject.getBoolean("error");
                if (error) {
                    String errorMsg = jsonObject.getString("error_msg");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();

                } else {
                    session.setLogin(true, username, email);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("tag", "login");
            hashMap.put("username", name);
            hashMap.put("password", password);
            return hashMap;
        }
    };
    queue.add(request);
}

Now I am writing my app for iOS and trying to replicate this in Swift. So far I have the following code:

let username = usernameTxt.text
        let password = passwordTxt.text
        let urlPath: String = "***"
        let url: NSURL = NSURL(string: urlPath)!
        let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

        request1.HTTPMethod = "POST"
        let stringPost="tag=login&username=" + username! + "&password=" + password! // Key and Value
        NSLog(stringPost)
        let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

        request1.timeoutInterval = 60
        request1.HTTPBody=data
        request1.HTTPShouldHandleCookies=false

        let queue:NSOperationQueue = NSOperationQueue()

        NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
            do {
               var jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
            } catch _ {}

        })

Now as someone new to iOS development and Swift in general, I have the following questions:

  1. What is the best way to replicate the progressDialog I use in Java in Swift, it must be visible until the request is complete and then it should be dismissed. I'm guessing this should be placed in the completionHandler, however I'm not sure which UI element to use for the progress Dialog.

  2. How do I obtain my response as a String and replicate the behaviour of the split function, and then convert the result of this into a jsonObject like I do in my Java code.

  3. What is the best way to replicate the Toast used to show the error message. I don't think using a dialog which must be closed with a button would be optimal here.

Thank you.


Solution

  • I am also developing Applications for Android and IOS. Here i Answered your three Problems which is faced by me also as a beginner. I hope this would help you.

    1) Use MBProgressHUD Link to replicate the progressDialog in Swift .There are two method to show and dismiss the progressDialog:

    Use showLoadingHUD() before making HTTP request

    private func showLoadingHUD() {
        let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
        hud.labelText = "Loading..."
    }
    

    And hideLoadingHUD() after receiving the response from server

    private func hideLoadingHUD() {
        MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
    }
    

    2) you can use Alamofire Link which can handle Network stuff And you can easily obtain response in String. Example:

     self.showLoadingHUD()
                    Alamofire.request(.GET, data, parameters: nil)
                        .response { (request, response, data, error) in
                            print(data) // if you want to check data in debug window.
                            let Result = NSString(data: data!, encoding: NSUTF8StringEncoding)
                            Result!.stringByReplacingOccurrencesOfString("\"", withString: "")
                            if(newResult == "1"){
                                self.navigationController!.popViewControllerAnimated(true)
                                JLToast.makeText("Success").show()
                            }
                            else if (newResult == "0"){
                                JLToast.makeText("Failed").show()
                            }
    
                            self.hideLoadingHUD()
    

    3) mankee Toas are used for a purpose of displaying information for short period of time and disappear themselves. Here we can use Android like Toast which is JLToast. Available on github .

    JLToast.makeText("Success").show()