I am currently learning swift 4 and would like to ask you to correct my code. (I would like to have a pattern for learning the "beautiful code").

My code gets data from the server in JSON format and creates a loggedUser object. Then I open the tabbed view controller with the correct application.

I'm trying to write an MVC compliant code.

My user login code:


import UIKit

class LoginViewController: UIViewController {

    // outlets
    @IBOutlet weak var textFieldLogin: UITextField!
    @IBOutlet weak var textFieldPassword: UITextField!
    let cms = Connect()

    @IBAction func btnLoginPressed(_ sender: Any) {
        if self.textFieldLogin.text?.isEmpty ?? true || self.textFieldPassword.text?.isEmpty ?? true  {
            self.errorLoginMessage(txt: "Uzupełnij wszystkie pola!!", title: "Błąd")
        } else {
            cms.checkUsersLogin(login: self.textFieldLogin.text, password: self.textFieldPassword.text, callback: { (data, error) in
                if error == nil{
                    if let dane = data {
                        do {
                            let decoder = JSONDecoder()
                            loggedUser = try decoder.decode(LoginUser.self, from: data!)

                            if ((loggedUser?.id ) == nil) {
                                let json = try? JSONSerialization.jsonObject(with: data!, options: [])

                                if let dictionary = json as? [String: Any] {
                                    if let komunikat = dictionary["komunikat"] as? String, let title = dictionary["error"] as? String {
                                        DispatchQueue.main.async {
                                            self.errorLoginMessage(txt: komunikat, title: title)
                                } else {
                                    DispatchQueue.main.async {
                                        self.errorLoginMessage(txt: "Podany login lub hasło jest błędny!!", title: "Błąd")
                            } else {
                                DispatchQueue.main.async {
                                    self.performSegue(withIdentifier: "toLoginUser", sender: self)
                        catch {
                            print("Error in decoder")
                    } else {
                        print("Error 103: \(data)")
                } else {
                    print("Error 104: \(error)")


    override func viewDidLoad() {


    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

    override func prepare(for segue: UIStoryboardSegue, sender: Any?){
        if segue.identifier == "toLoginUser" {


    func errorLoginMessage(txt: String, title: String){
        let ac = UIAlertController(title: title, message: nil, preferredStyle: .alert)
        let alertController = UIAlertController(title: title, message: txt, preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: { (action: UIAlertAction!) in

        self.present(alertController, animated: true, completion: nil)

    override var prefersStatusBarHidden: Bool {
        return true

My class for connecting to the server and handling requests:


import Foundation

public struct Connect {
    let serverAdress = "http://myserwer.pl/"
    typealias Answer = (Data?, Error?) -> Void

    func getJsonFromServer(parameters: String, responseRequest: @escaping Answer) {
        guard let Url = URL(string: self.serverAdress + "kartyEndpoint.qbpage" + parameters) else { return }
        URLSession.shared.dataTask(with: Url) { (data, response, error) in
            if error == nil {
                guard let data = data else {
                    print("Error 100:  \(error)")
                    responseRequest(nil, error)
                print("R>" + self.serverAdress + "kartyEndpoint.qbpage" + parameters)
                do {
                    responseRequest(data, nil)

                } catch let err {
                    print("Error 101: ", err)
                    responseRequest(nil, err)
            } else{
                print("Error 102: Problem with download data")

    func checkUsersLogin(login: String?, password: String?, callback: @escaping Answer) {
        getJsonFromServer(parameters: "?action=LOGOWANIE&login=\(login!)&password=\(password!)", responseRequest: callback)

  • \$\begingroup\$ Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via edit. Maybe you missed the placeholder on the title element: "State the task that your code accomplishes. Make your title distinctive.". Also from How to Ask: "State what your code does in your title, not your main concerns about it.". \$\endgroup\$ – Sᴀᴍ Onᴇᴌᴀ Apr 25 '18 at 19:14
  • \$\begingroup\$ Thank you for your answer. My code gets data from the server in json format and creates a loggedUser object. Then I open the tabbed view controler with the correct application. I would like you to evaluate my code and make any modifications to my code. I would like to learn to write a nice code on this basis \$\endgroup\$ – Łukasz Betta Apr 25 '18 at 19:23
  • \$\begingroup\$ my code works correctly. I would like to ask you only for the correction of the style of code writing, code review, improvement of syntax, etc. \$\endgroup\$ – Łukasz Betta Apr 25 '18 at 20:32
  • 1
    \$\begingroup\$ You don't need to say that, it's what we do here. I edited it a bit to reflect that \$\endgroup\$ – Raystafarian Apr 26 '18 at 5:03
  • \$\begingroup\$ It would be helpful to know what the JSON response looks like. – Translating the messages to english would make them understandable to a broader audience. \$\endgroup\$ – Martin R Apr 26 '18 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.