[ios] 연락처 기반 실시간 알림 서비스

iOS 애플리케이션에서 연락처 기반으로 실시간 알림 기능을 구현하고 싶다면, 다음 단계를 따를 수 있습니다.

목차

  1. Firebase를 이용한 실시간 알림 설정
  2. 연락처 데이터 가져오기
  3. 알림 메시지 생성과 전송
  4. 연락처 동의 요청 및 처리

Firebase를 이용한 실시간 알림 설정

먼저, Firebase Cloud Messaging(FCM)을 이용하여 iOS 앱에 실시간 알림을 설정합니다. Firebase 콘솔에서 프로젝트를 생성하고, FCM을 설정한 후 서버 키를 발급받습니다.

// AppDelegate.swift
import Firebase

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    FirebaseApp.configure()
    // ...
    return true
}

연락처 데이터 가져오기

연락처에 접근하여 사용자의 연락처 목록을 가져오기 위해 Contacts Framework를 사용합니다.

// ContactManager.swift
import Contacts

class ContactManager {
    static let shared = ContactManager()
    
    func fetchContacts() -> [CNContact] {
        var contacts = [CNContact]()
        let store = CNContactStore()
        let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]
        let request = CNContactFetchRequest(keysToFetch: keysToFetch as [CNKeyDescriptor])
        
        do {
            try store.enumerateContacts(with: request, usingBlock: { (contact, stop) in
                contacts.append(contact)
            })
        } catch {
            print("Error fetching contacts: \(error)")
        }
        
        return contacts
    }
}

알림 메시지 생성과 전송

사용자의 연락처 목록을 가져온 후, 해당 사용자들에게 알림 메시지를 전송합니다. FCM을 사용하여 메시지를 생성하고 전송합니다.

// NotificationManager.swift
import Firebase

class NotificationManager {
    static let shared = NotificationManager()
    
    func sendNotification(to user: String, with message: String) {
        let data: [String: Any] = [
            "to": user,
            "notification": [
                "title": "새로운 메시지",
                "body": message
            ]
        ]
        
        let url = URL(string: "https://fcm.googleapis.com/fcm/send")
        var request = URLRequest(url: url!)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("key=YOUR_SERVER_KEY", forHTTPHeaderField: "Authorization")
        
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
        } catch let error {
            print("Error serializing JSON: \(error.localizedDescription)")
        }
        
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            // Handle response
        }.resume()
    }
}

연락처 동의 요청 및 처리

마지막으로, 사용자의 연락처에 접근하기 위해 Info.plist 파일에 관련 권한을 추가하고, 동의를 요청하여 처리합니다.

<key>NSContactsUsageDescription</key>
<string>연락처에 접근하기 위해 권한이 필요합니다.</string>

위의 코드를 따라하면, iOS 앱에서 연락처 기반으로 실시간 알림 서비스를 구현할 수 있습니다.

참고 자료