iOS 기본 (swift)
[iOS - swift] 5. 메시지 전달 (alert, actionSheet)
jake-kim
2020. 4. 3. 16:04
* 메시지 전달의 종류
- 단순 알림창
- 로컬 알림
- 서버 알림 (여기서는 다루지 않음)
1. 단순 알림창
- 앱이 실행중에만 가능 (fore ground에서만 가능)
1) 생성
- DispatchQueue.main.async : 메인스레드(UI관련)에서도 async작업을 사용할 수 있도록 하는 것
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
DispatchQueue.main.async {
let alert = UIAlertController(title:"알림",
message: "UIAlertController알림창",
preferredStyle: .alert) // .actionSheet사용가능
let ok = UIAlertAction(title: "ok", style: .default)
let cancel = UIAlertAction(title: "cancel", style: .cancel)
let importantOk = UIAlertAction(title: "ok!?", style: .destructive) // 빨간색으로 표시
alert.addAction(ok)
alert.addAction(cancel)
alert.addAction(importantOk)
self.present(alert, animated: true)
}
|
2) 텍스트 필드 생성 및 접근
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
alert.addTextField(configurationHandler: { (tf) in
tf.placeholder = "아이디"
tf.isSecureTextEntry = true
})
alert.addTextField(configurationHandler: { (tf) in
tf.placeholder = "암호"
tf.isSecureTextEntry = true
})
let ok = UIAlertAction(title: "ok", style: .default) { (_) in
guard let id = alert.textFields?[0].text else {return}
guard let pw = alert.textFields?[1].text else {return}
}
|
2. 로컬알림
- UNMutableNotificationContent() 객체, UNUserNotificationCenter인스턴스 이용
- 정한 시간 후 자동 알림 기능
- fore ground에서는 실행이 안되고 오직 back ground에서만 실행가능(홈버튼을 누른 경우)
1) 생성
|
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
|
// AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let notiCenter = UNUserNotificationCenter.current()
notiCenter.requestAuthorization(options: [.alert,.sound,.badge]) {(didAllow, e) in}
return true
}
// ViewController.swift
@IBAction func btnAction(_ sender: Any) {
let content = UNMutableNotificationContent()
content.title = "This is title : mustang"
content.subtitle = "This is Subtitle : sub"
content.body = "This is Body : body"
content.badge = 123
content.userInfo = ["name":"홍길동"] // 데이터 넘겨줄 때 사용할 정보
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats:false)
let request = UNNotificationRequest(identifier: "timerdone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
|
2) 사용자가 클릭한 것을 처리
- delegate = self로 등록
- NUUserNotificationDelegate 프로토콜 구현
- userNotificationCenter(_:didReceive..)구현
|
1
2
3
4
5
6
7
8
9
10
11
12
|
// AppDelegate.swift에서 application(..didFinishLanching)에
notiCenter.delegate = self 넣은 후,
// AppDelegate.swift, 클릭했을 때의 이벤트 처리 지정했던 userInfo 불러오기
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
if response.notification.request.identifier == "timerdone" {
let userInfo = response.notification.request.content.userInfo
NSLog("값 = \(userInfo["name"])")
}
}
}
|
* 사용자에게 권한 허용 요청 관련 방법
-앱 어플리케이션 자체를 의미하는 UIApplication 싱글턴 객체를 이용
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// 인스턴스 참조
let application = UIApplication.shared
// 사용자에 권한 요청할 부분
let setting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
// 요청
application.registerUserNotificationSettings(setting)
// 사용자가 Don't Allow를 한 경우, .none으로 표현
let check = application.currentUserNotificationSettings
if(check == .none){
// 거절한 경우 처리
}
|