Created
May 5, 2020 09:50
-
-
Save gladilindv/5abbf7ba0514eba52a8da0f2a4e9c03a to your computer and use it in GitHub Desktop.
Swift observable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import SwiftUI | |
import Combine | |
class HttpAuth: ObservableObject { | |
@Published var authenticated = false | |
func postAuth(username: String, password: String) { | |
guard let url = URL(string: "http://mysite/login") else { return } | |
let body: [String: String] = ["username": username, "password": password] | |
let finalBody = try! JSONSerialization.data(withJSONObject: body) | |
var request = URLRequest(url: url) | |
request.httpMethod = "POST" | |
request.httpBody = finalBody | |
request.setValue("application/json", forHTTPHeaderField: "Content-Type") | |
URLSession.shared.dataTask(with: request) { (data, response, error) in | |
guard let data = data else { return } | |
let resData = try! JSONDecoder().decode(ServerMessage.self, from: data) | |
print(resData.res) | |
if resData.res == "correct" { | |
DispatchQueue.main.async { | |
self.authenticated = true | |
} | |
} | |
}.resume() | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
@State private var username: String = "" | |
@State private var password: String = "" | |
@ObservedObject var manager = HttpAuth() | |
var body: some View { | |
VStack(alignment: .leading) { | |
if self.manager.authenticated { | |
Text("Correct!").font(.headline) | |
} | |
Spacer() | |
Text("Username") | |
TextField("placeholder", text: $username) | |
.textFieldStyle(RoundedBorderTextFieldStyle()) | |
.border(Color.green) | |
.autocapitalization(.none) | |
Text("Password") | |
SecureField("placeholder", text: $password) | |
.textFieldStyle(RoundedBorderTextFieldStyle()) | |
.border(Color.green) | |
Button(action: { | |
self.manager.postAuth(username: self.username, password: self.password) | |
}) { | |
HStack{ | |
Spacer() | |
Text("Login") | |
Spacer() | |
} | |
.accentColor(Color.white) | |
.padding(.vertical, 10) | |
.background(Color.red) | |
.cornerRadius(5) | |
.padding(.horizontal, 40) | |
} | |
Spacer() | |
}.padding() | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment