Quản lý liên lạc và định dạng dữ liệu trong iOS

Giới thiệu

Trong quá trình phát triển ứng dụng iOS, việc xử lý hiệu quả dữ liệu liên lạc đóng vai trò quan trọng trong việc tạo ra trải nghiệm người dùng mượt mà. Bài viết này sẽ hướng dẫn bạn các kỹ thuật thực tế để quản lý và định dạng thông tin liên lạc một cách chuyên nghiệp.

Trích xuất tên đầy đủ của liên lạc

Để lấy thông tin tên đầy đủ, chúng ta sử dụng CNContactFormatter kết hợp với phương thức firstUnifiedContactMatching(name:toFetch:output:). Đầu tiên, cần khai báo các thuộc tính cần truy xuất thông qua descriptorForRequiredKeys(for:).

Ví dụ mã nguồn
let requiredKeys = CNContactFormatter.descriptorForRequiredKeys(for: .fullName)
contactStore.firstUnifiedContactMatching(name: "john", toFetch: [requiredKeys]) { result in
    switch result {
    case .success(let contact):
        if let fullName = CNContactFormatter().string(from: contact) {
            print("Tên đầy đủ: \(fullName)")
        }
    case .failure(let error):
        print("Lỗi truy xuất: \(error.localizedDescription)")
    }
}

Xử lý tên phiên âm của liên lạc

Đối với các ứng dụng hỗ trợ đa ngôn ngữ, việc hiển thị tên phiên âm là cần thiết. Sử dụng CNContactFormatterStyle.phoneticFullName để trích xuất và định dạng tên theo cách phát âm của ngôn ngữ tương ứng.

Ví dụ mã nguồn
let phoneticStyle = CNContactFormatterStyle.phoneticFullName
let keysToFetch = CNContactFormatter.descriptorForRequiredKeys(for: phoneticStyle)

contactStore.firstUnifiedContactMatching(name: "julian", toFetch: [keysToFetch]) { result in
    guard case .success(let contact) = result else { return }
    
    if let phoneticName = CNContactFormatter.string(from: contact, style: phoneticStyle) {
        print("Tên phiên âm: \(phoneticName)")
    }
}

Định dạng địa chỉ bưu điện

Để hiển thị địa chỉ theo định dạng phù hợp với từng khu vực, CNPostalAddressFormatter cung cấp giải pháp toàn diện. Lớp này tự động điều chỉnh định dạng theo locale của thiết bị.

Ví dụ mã nguồn
let addressKeys = [CNContactPostalAddressesKey as NSString]

contactStore.firstUnifiedContactMatching(name: "john", toFetch: addressKeys) { result in
    guard case .success(let contact) = result else { return }
    
    guard let postalAddress = contact.postalAddresses.first?.value else {
        print("Không tìm thấy địa chỉ")
        return
    }
    
    let addressFormatter = CNPostalAddressFormatter()
    let formattedAddress = addressFormatter.string(from: postalAddress)
    print("Địa chỉ: \(formattedAddress)")
}

Tích hợp giao diện chọn liên lạc có sẵn

Thư viện ContactsUI cung cấp sẵn CNContactPickerViewController cho phép người dùng chọn liên lạc một cách trực quan. Đây là giải pháp tiết kiệm thời gian so với việc tự xây dựng giao diện.

Ví dụ mã nguồn
let pickerController = CNContactPickerViewController()
pickerController.delegate = self
present(pickerController, animated: true)

Hỗ trợ chọn nhiều liên lạc

Để cho phép người dùng chọn nhiều liên lạc cùng lúc, cần cấu hình thuộc tính predicateForSelectionOfProperty. Điều này giới hạn các trường thông tin mà người dùng có thể truy cập.

Ví dụ mã nguồn
func contactPicker(_ picker: CNContactPickerViewController, 
                   didSelect contacts: [CNContact]) {
    print("Đã chọn \(contacts.count) liên lạc")
    
    for contact in contacts {
        if let name = CNContactFormatter().string(from: contact) {
            print("- \(name)")
        }
    }
}

Thẻ: iOS contacts-framework cncontact cocoa-touch mobile-development

Đăng vào ngày 30 tháng 6 lúc 08:23