Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- node.js
- SWIFT
- rxswift
- swiftarchitecture
- Java
- vuejs
- Vue
- 12969
- 스위프트
- UITabBarController
- 스위프트기초
- programmers12969
- 스위프트아키텍처
- STS3
- webviewControll
- NotificationCenter정의
- webview javascript
- HTTP
- 비동기프로그래밍
- JavaScript
- URLSession
- WKWebView
- MVVM
- UIKit
- WebView
- Vue.js
- ios
- Node
- STS
- Spring
Archives
- Today
- Total
Monti
Swift - UserDefault를 활용한 자동 로그인 본문
😀
UserDefaults 활용 자동로그인
Web
Front(Html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function autoLogin(uid, password) {
document.getElementById("uid").value = uid;
document.getElementById("password").value = password;
document.getElementById("autoLogin").checked = true;
onSubmit()
}
function onSubmit() {
let uid = document.getElementById("uid").value
let password = document.getElementById("password").value
let autoLogin = document.getElementById("autoLogin").checked
let sendData =
{
"id" : uid,
"password" : password
}
$.ajax({
url: "http://127.0.0.1:3000",
type: "POST",
dataType: "JSON",
data: sendData,
success: function(data) {
webkit.messageHandlers.data.postMessage(JSON.stringify(data))
// 자동 로그인 체크일 때
if(autoLogin){
console.log("autoLogin")
webkit.messageHandlers.isAutoLogin.postMessage(JSON.stringify(sendData))
}
document.getElementById("sessionId").innerHTML = data.id
document.getElementById("tokken").innerHTML = data.token.accessToken
document.getElementById("isAutoLogin").innerHTML = autoLogin
},
error: function (request, status, error) {
console.log(status)
console.log(error)
}
})
}
</script>
</head>
<body>
<table>
<tr>
<td>ID</td>
<td><input type="text" id="uid" name="uid" placeholder="아이디를 입력해주세요"></td>
</tr>
<tr>
<td>PW</td>
<td><input type="password" id="password" name="password" placeholder="비밀번호를 입력해주세요"></td>
</tr>
</table>
<div><input type="checkbox" id="autoLogin" name="autoLogin">자동로그인</div>
<div><button type="button" onclick="onSubmit()">로그인</button></div>
<div>
로그인 정보
</div>
<table>
<tr>
<th>ID</th>
<th>tokken</th>
<th>자동로그인유무</th>
</tr>
<tr>
<td><p id="sessionId" name="sessionId"></p></td>
<td><p id="tokken" name="tokken"></p></td>
<td><p id="isAutoLogin" name="isAutoLogin"></p></td>
</tr>
</table>
</body>
</html>
exrpess server
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', function(req, res) {
let id = req.body.id;
let password = req.body.password;
console.log(req.body)
let accessToken = "1234567"
let refreshToken = "2345678"
let user = {
id : id,
token: {
accessToken : accessToken,
refreshToken : refreshToken
}
}
try {
if(id == "test" && password == "1234") {
res.send(user)
} else {
let error = { error : "잘못된 아이디 혹은 비밀번호"}
res.status(401).send(error)
}
} catch (error) {
console.log(error)
}
res.send()
});
module.exports = router;
Native Web 연결 초기화
func loadWebView() {
guard let url = URL(string: "http://127.0.0.1:8080/login.html") else {
navigationController?.popViewController(animated: true)
return
}
view = webView
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
}
func setupWebView() {
let contentController = WKUserContentController()
contentController.add(self, name: "data")
contentController.add(self, name: "isAutoLogin")
autoLogin(contentController: contentController)
let configuration = WKWebViewConfiguration()
configuration.userContentController = contentController
webView = WKWebView(frame: .zero, configuration: configuration)
}
UserDefaults 저장 값 존재 시 로그인 함수 호출
func autoLogin(contentController: WKUserContentController) {
let uid = UserDefaults.standard.string(forKey: "auto_id") ?? ""
let password = UserDefaults.standard.string(forKey: "auto_password") ?? ""
if uid != "" && password != "" {
let userScript = WKUserScript(source: "document.getElementById('uid').value = '\(uid)'", injectionTime: .atDocumentEnd, forMainFrameOnly: true)
contentController.addUserScript(userScript)
let passwordScript = WKUserScript(source: "document.getElementById('password').value = '\(password)'", injectionTime: .atDocumentEnd, forMainFrameOnly: true)
contentController.addUserScript(passwordScript)
let autoLoginScript = WKUserScript(source: "document.getElementById('autoLogin').checked = true", injectionTime: .atDocumentEnd, forMainFrameOnly: true)
contentController.addUserScript(autoLoginScript)
let login = WKUserScript(source: "onSubmit()", injectionTime: .atDocumentEnd, forMainFrameOnly: true)
contentController.addUserScript(login)
}
}
Web Bridge 설정
extension ViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
switch message.name {
case "data":
guard let body = message.body as? String else { return }
let dicData = stringToDicData(data: body)
print("sessionId")
print(dicData["id"]!)
break
case "isAutoLogin":
guard let body = message.body as? String else { return }
let dicData = stringToDicData(data: body)
UserDefaults.standard.set(dicData["id"]!, forKey: "auto_id")
UserDefaults.standard.set(dicData["password"]!, forKey: "auto_password")
print(UserDefaults.standard.string(forKey: "auto_id") ?? "")
print(UserDefaults.standard.string(forKey: "auto_password") ?? "")
break;
default:
break
}
}
func stringToDicData(data: String) -> Dictionary<String, Any> {
var dicData : Dictionary<String, Any> = [String : Any] ()
do {
dicData = try JSONSerialization.jsonObject(with: Data(data.utf8), options: []) as! [String: Any]
} catch {
print(error.localizedDescription)
}
return dicData
}
}
Login 테스트
Tobe - Cookie 설정
----
'IOS > Swift' 카테고리의 다른 글
swift) webview-2 (자바스크립트 버튼 클릭 이벤트 핸들링) (0) | 2022.10.08 |
---|---|
swift) webview-1 (0) | 2022.10.08 |
swift - WKWebView 자동로그인 구현 (0) | 2022.10.03 |
Swift URLSession HTTP 통신 - 2 (0) | 2022.09.30 |
Swift URLSession HTTP 통신 - 1 (0) | 2022.09.30 |
Comments