如何将所有 phone 联系人传递给 swift 中的 JSON API

How to pass all phone contacts to JSON API in swift

我能够在 table 视图中获取所有 phone 联系人。

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

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

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

代码:这里 api 和给定的 phone 数字都在工作..这里用我的代码你也可以检查 JSON 响应..但是我需要将所有 phone 联系人发送到 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("\r\n".data(using: .utf8)!)
            }

            body.append("--\(boundary)\r\n".data(using: .utf8)!)

            guard
                rawName.canBeConverted(to: encoding),
                let disposition = "Content-Disposition: form-data; name=\"\(rawName)\"\r\n".data(using: encoding) else {
                throw MultipartFormDataEncodingError.name(rawName)
            }
            body.append(disposition)

            body.append("\r\n".data(using: .utf8)!)

            guard let value = rawValue.data(using: encoding) else {
                throw MultipartFormDataEncodingError.value(rawValue, name: rawName)
            }

            body.append(value)
        }

        body.append("\r\n--\(boundary)--\r\n".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 { [=10=].phoneNumbers }.map { [=10=].value.stringValue }

然后你就可以像现在这样发送phNumArray了。

在评论中回答问题。
对于联系的其他属性,你可以这样做

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

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

您可以获得可用属性列表here
查找 here 可用键。