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:
login.swift
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 {
dump(loggedUser)
self.performSegue(withIdentifier: "toLoginUser", sender: self)
}
}
}
catch {
print("Error in decoder")
}
} else {
print("Error 103: \(data)")
}
} else {
print("Error 104: \(error)")
}
})
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.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:
connect.swift
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)
return
}
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")
}
}.resume()
}
func checkUsersLogin(login: String?, password: String?, callback: @escaping Answer) {
getJsonFromServer(parameters: "?action=LOGOWANIE&login=\(login!)&password=\(password!)", responseRequest: callback)
}
}