- 사용자에게 메시지 전달하기
- UIAlertController
- 생성자에 제목, 메시지, preferredStyle(.alert, .actionSheet)을 써준다.
- UIAlertAction을 생성해 UIAlertController에 addAction()해 줌으로써 버튼과 실행 구문을 추가한다.
- 준비가 끝났으면 present()
- addTextField로 텍스트 필드 추가 가능. 이후 UIAlertController객체에서 텍스트 필드를 참조.
- 푸시 메시지(로컬) : iOS 10.0이후 부터는 UserNotifications프레임워크를 import하여 사용한다.
- 먼저 사용자 동의를 얻어 줄 것.
let notiCenter = UNUserNotificationCenter.current()
notiCenter.requestAuthorization(options: [.alert, .badge, .sound]) { (didAllow, e) in
// allow, not allow에 따른 처리
}
- 발송 : UNMutableNotificationContent, UNTimeIntervalNotificationTrigger를 이용해
UNNotificationRequest를 만든 후 UNUserNotificationCenter.add()한다.
- 이 때 UNUserNotificationCenter객체는 싱글톤이라 맘대로 생성하면 안되고
UNUserNotificationCenter.current()로 참조만 할 수 있다.
- UNUserNotificationCenter에 delegate로 UNUserNotificationCenterDelegate를
구현하여 주입하면 그에 따른 액션을 지정할 수 있다.
- UNUserNotificationCenter에 add()함으로써 발신이 끝남
ex)
let nContent = UNMutableNotificationContent()
nContent.badge = 1
nContent.title = “로컬 알림 메시지”
nContent.subtitle = “앱을 열어주세요!”
nContent.body = “나가지마ㅠ”
nContent.sound = UNNotificationSound.default
nContent.userInfo = [“name”: “덕현”]
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: “wakeup”,
content: nContent, trigger: trigger)
let notiCenter = UNUserNotificationCenter.current()
notiCenter.delegate = self
notiCenter.add(request)
- 수신 : 수신 처리는 앞서 delegate를 구현하여 주입해준 뷰컨트롤러 등에서 한다.
- 앱 실행중에는 알림이 와도 표시되지 않는데, 표시하게 하기 위해 UNUserNotificationCenterDelegate의
userNotificationCenter(_:willPresent:withCompletionHandler:)를 구현한다.
전처리 등 해줄 것 다 해주고 completionHandler([.alert,.badge,.sound])를 호출하면
비로소 알림이 표시되는 것이다.
- 알림을 눌렀을 때 어떠한 액션을 실행하려면
userNotificationCenter(_:didReceive:withCompletionHandler:)를 구현한다.
하고싶은 액션 다 해준 후 completionHandler()를 호출해주면 끝.
- Delegate패턴 : 하나의 객체가 처리해야 하는 태스크중 일부를 다른 객체에게 위임하는 패턴.
- IOS에서 특히 많이 사용하는 패턴임.
- 델리게이트를 위한 프로토콜을 정의하고, 메소드를 사용하여 특정 이벤트가 발생했을 때 알려준다.
- 프로토콜을 구현한 구현체는 이벤트가 발생했을 때의 실행문을 구현한다.
- 태스크 중 일부를 분리해 놓고 교신해가며 일을 나눠처리하는 느낌.
- Android에서 EditText에 whatcher를 붙이듯 IOS에서도 UITextFieldDelegate같이 델리게이트를 붙일 수 있다.
- UIImagePickerController를 이용해 사진을 찍거나 선택하고, delegate에서 이를 받을 수 있다.
이 delegate는 UIImagePickerControllerDelegate, UINavigationControllerDelegate를 구현해야 한다.
UIImagePickerController를 생성한 후 present방식으로 연다. 컨트롤러 객체에 delegate를 주입한다.
이미지를 가져오는 작업이 끝나면 UIImagePickerControllerDelegate의 imagePickerController메소드가
호출된다. 여기서 info[UIImagePickerController.InfoKey.editedImage] as? UIImage구문을 통해
이미지를 가져올 수 있다.
- First Responder : UIWindow는 First Responder라는 객체 포인터를 가지고 있는데,
이는 터치 등 특정 이벤트 발생시 우선적으로 응답할 객체의 Focus를 의미한다.
- UIResponder를 상속받은 객체들을 이 클래스에 정의된 becomeFirstResponder()를 호출하여 최초응답자가 될 수 있으며
해제할 때에는 resignFirstResponder()를 호출한다.
- 스토리보드의 뷰 컨트롤러 도크의 두번째 아이콘을 뷰에 연결해 놓으면 그 뷰가 최초응답자로 지정된다.
- Notification패턴 : Notification Center라는 싱글톤 객체를 통해 이벤트들의 발생여부를 옵저버를 등록한 객체들에게
POST하는 방식으로 사용(broadcast와 비슷)
- 발송 : NotificationCenter.default.post(name: NSNotification.Name(“NOTI_TEXT”),
object: nil, userInfo: [“text”: text])
- object또는 userInfo라는 딕셔너리 타입에 입력해 준다
- 수신 준비 : 옵저버 등록
- NotificationCenter.default.addObserver(
self, selector: #selector(changeText(_:)),
name: NSNotification.Name(“NOTI_TEXT”), object: nil)
- selector에는 수신할 때 호출할 함수를 작성. 이 함수는 @objc를 붙여야 하며
파라메터 타입으로 Notification을 써야함.
- #selector를 붙일 것
- 수신 : addObserver에 selector로 넣어준 함수를 정의한다.
- Notification의 userInfo를 참조할 수 있다.
ex)
@objc func changeText(_ noti: Notification) {
guard let userInfo = noti.userInfo, let text = userInfo[“text”] as? String
else { return }
label.text = text
}
- 수신 종료 : deinit블럭에서 수신 종료를 명시한다.
- NotificationCenter.default.removeObserver(
self, name: NSNotification.Name(“NOTI_TEXT”), object: nil)