PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 6, 2022

[FIXED] How to pass all phone contacts to JSON API in swift

 November 06, 2022     contacts, json, swift     No comments   

Issue

I am able to fetch all phone contacts in a table view.

I need to pass all phone contacts in JSON URL parameter called contactsList, but I am unable to pass all phone contacts to Json parameter contactsList

If I send individual phone number like below code, it's coming

but i need to send all my phone contacts to JSON API

code: here the api and given phone numbers all are working.. here with my code you can check JSON response as well.. but i need to send all phone contacts to 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)
}

EDIT: OUT PUT: here how do i get each contact userName and tagged values

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;
.......

Solution

To convert the contact array as an array of string you can do this

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

Then you can send phNumArray as it is now.

Answer for question in the comment.
To other properties of contact, you can do something like this

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

Obviously you need to use proper keys in this case CNContactGivenNameKey, CNContactFamilyNameKey during contact fetch.

You can get the list of available properties here
Look here for available keys.



Answered By - Nazmul Islam
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing