如何在swift中将所有电话联系人传递给JSON API



我可以在表格视图中获取所有电话联系人。

我需要在名为contactsList的JSON URL参数中传递所有电话联系人,但我无法将所有电话联系人传递给JSON参数contactsList

如果我像下面的代码一样发送个人电话号码,它就来了

但我需要将我所有的电话联系人发送到JSON API

代码:这里的api和给定的电话号码都在工作。。在这里使用我的代码,您也可以检查JSON响应。。但我需要将所有的电话联系发送到API

import UIKit
import Contacts
class ContactsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var joinersTableView: UITableView!
var contacts = [CNContact]()
var phNumArray  = ["5555555544", "1212121212"]
var taggedStatus: String?
override func viewDidLoad() {
super.viewDidLoad()
joinersTableView.register(UINib(nibName: "ContactsTableViewCell", bundle: nil), forCellReuseIdentifier: "ContactsTableViewCell")
ContactsModel.shared.getLocalContacts {(contact) in
self.contacts.append(contact!)
}
joinersTableView.reloadData()
self.callPostApi()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contacts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell: ContactsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "ContactsTableViewCell") as! ContactsTableViewCell
cell.nameLbl.text    = contacts[indexPath.row].givenName + " " + contacts[indexPath.row].familyName
cell.phNUmLbl.text = contacts[indexPath.row].phoneNumbers.first?.value.stringValue

return cell

}
func callPostApi() {
let url            = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")!
var request        = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("F139424D-C749-42F6-B804-21BD17E28CE0", forHTTPHeaderField: "deviceid")
request.setValue("c913136e897b419bab20746de7baab62", forHTTPHeaderField: "key")
request.setValue("personal", forHTTPHeaderField: "userType")
try? request.setMultipartFormData(["contactsList": "(phNumArray)"], encoding: .utf8)

URLSession.shared.dataTask(with: request) { data, _, _ in
if let data = data, let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print("contacts JSON (jsonObj)")
let phnDict = jsonObj as? [String : Any]

print("each phone number1111111 (phnDict)")
}
}.resume()
}
}
extension URLRequest {
public mutating func setMultipartFormData(_ parameters: [String: String], encoding: String.Encoding) throws {
let makeRandom = { UInt32.random(in: (.min)...(.max)) }
let boundary = String(format: "------------------------%08X%08X", makeRandom(), makeRandom())
let contentType: String = try {
guard let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(encoding.rawValue)) else {
throw MultipartFormDataEncodingError.characterSetName
}
return "multipart/form-data; charset=(charset); boundary=(boundary)"
}()
addValue(contentType, forHTTPHeaderField: "Content-Type")
httpBody = try {
var body = Data()
for (rawName, rawValue) in parameters {
if !body.isEmpty {
body.append("rn".data(using: .utf8)!)
}
body.append("--(boundary)rn".data(using: .utf8)!)
guard
rawName.canBeConverted(to: encoding),
let disposition = "Content-Disposition: form-data; name="(rawName)"rn".data(using: encoding) else {
throw MultipartFormDataEncodingError.name(rawName)
}
body.append(disposition)
body.append("rn".data(using: .utf8)!)
guard let value = rawValue.data(using: encoding) else {
throw MultipartFormDataEncodingError.value(rawValue, name: rawName)
}
body.append(value)
}
body.append("rn--(boundary)--rn".data(using: .utf8)!)
return body
}()
}
}
public enum MultipartFormDataEncodingError: Error {
case characterSetName
case name(String)
case value(String, name: String)
}

编辑:输出:这里我如何获得每个联系人的userNametagged

contacts JSON ["(408) 555-5270": {
oniTaag = 0;
profilePic = "<null>";
tagged = 0;
userId = "<null>";
userName = "<null>";
userType = personal;
}, "555-522-8243": {
oniTaag = 0;
profilePic = "<null>";
tagged = 0;
userId = "<null>";
userName = "<null>";
userType = personal;
}, "(408) 555-3514": {
oniTaag = 0;
profilePic = "<null>";
tagged = 0;
userId = "<null>";
userName = "<null>";
userType = personal;
}, "555-478-7672": {
oniTaag = 0;
profilePic = "<null>";
tagged = 0;
userId = "<null>";
userName = "<null>";
userType = personal;
.......

要将联系人数组转换为字符串数组,可以执行此

let phNumArray = contacts.flatMap { $0.phoneNumbers }.map { $0.value.stringValue }

然后,您可以按现在的状态发送phNumArray。

回答评论中的问题
对于联系人的其他属性,您可以执行类似于此的操作

for contact in contacts {
print(contact.givenName)
print(contact.familyName)
}

显然,在这种情况下,您需要在获取联系人时使用正确的密钥CNContactGivenNameKeyCNContactFamilyNameKey

您可以在此处获得可用属性的列表
在此处查找可用密钥。

最新更新