Tag Archives: ios


Fetch Contacts From Native Phonebook

Import Contacts In iOS

Contacts are We are going to use built in Contacts.framework to import all contacts in our app. To display a list of contacts, you must have access to the user’s address book. Apple does a great job of protecting the user’s privacy, so you can’t read any of their contacts’ data without asking the user for permission. Similar restrictions apply to access the user’s camera, location, photos, and more.

Whenever we need access to privacy-sensitive information, you are required to specify this in your app’s Info.plist file. This file keeps track of many of your app’s properties, such as its display name, supported interface orientations, and, in the case of accessing a user’s contacts, Info.plist also contains information about why you need access to the user’s contacts.

Let’s go step by step:-

  • Add usage description in Info.plist file for contacts.

Open Plist file and click on plus button to add new row for contact usage description.

Add Privacy – Contacts Usage Description in key

Select Type as String

Write the usage purpose of contacts in your app.

  • Import Contacts Framework in your class.

import Contacts


  •  Request for Contact permission

func getAuthStatus() -> CNAuthorizationStatus{


        return CNContactStore.authorizationStatus(for: .contacts)



    func requestForAccess(_ completionHandler: @escaping (_ accessGrandted: Bool, _ authStatus: CNAuthorizationStatus) -> Void)  {


        let authorizationStatus = getAuthStatus()


        switch authorizationStatus {

        case .authorized:


            completionHandler(true, CNAuthorizationStatus.authorized)



        case .notDetermined:

            let store = CNContactStore()

            store.requestAccess(for: .contacts, completionHandler: { (authorized: Bool, error: Error?) in


                if authorized {

                    completionHandler(true, CNAuthorizationStatus.authorized)


                else {


                    if self.getAuthStatus() == CNAuthorizationStatus.denied {

                        completionHandler(false, CNAuthorizationStatus.denied)



            } )




        case .denied :


            completionHandler(false, CNAuthorizationStatus.denied)





            completionHandler(false, CNAuthorizationStatus.notDetermined)





Above two function will check Contact authorisation status. If not determined it will show alert for contact permission. Keep in mind you can ask Contact permission only once. Once user denied you can just open Setting screen for enable Contact permission.

  • Fetch Contact Using CNContactStore:-

do {

            let store = CNContactStore()

            var results = [CNContact]()

            let containers = try store.containers(matching: nil)

            for container in containers {

                let predicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier)



                let keyToFetch = [CNContactIdentifierKey,

                                  CNContactFormatter.descriptorForRequiredKeys(for: .fullName),






                                  CNContactOrganizationNameKey] as [Any]

                let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keyToFetch as! [CNKeyDescriptor])

                results.append(contentsOf: contacts)


return results





            // print("Error1 is \(error)")




We create a CNContactStore instance and this object is used to communicate directly with the Contacts system on iOS. In this method, we wrap our code in a do-catch statement because two of the methods we use are throwing methods.We can retrieve different values using different Keys like first name, last name, contact image, mobile number, address, emails etc. We then create an array that contains a number of constant keys. These keys directly relate to the information your app has access too.

There is different container Group in Native phonebook. We can retrieve Contacts from different Container according our need. Here we are retrieving contacts of all Groups using store.containers(matching: nil) and iterate it one by one to fetch contacts.

store.unifiedContacts will return array of CNContact which you can store in Your app data or in your app’s database and display contacts In your own tableview Format.


In iOS 13, apple have added a new entitlement that is needed if you wish to access the notes for contacts. The entitlement is com.apple.developer.contacts.notes. You can request permission to use this entitlement for an app being put in the App Store.

The reason it was added is primarily for privacy reasons — the notes field can contain any information you might have on the contact; and a lot of times this information is significantly more sensitive than just the contact information.


Happy Coding.

Dial USSD code in iOS?

How to Dial USSD code in iOS?

What is USSD?
USSD (Unstructured Supplementary Service Data) is a communications protocol used by GSM cellular telephones to communicate with the mobile network operator’s computers.

Generally, the USSD code is used by apps for start Call Forwarding, To get some system info, USSD based banking services, etc.

Previously, iOS didn’t allow to dial special chars like “*” and “#” programmatically from the iOS app, to prevent users from malicious redirecting phone calls or changing the behavior of a phone or account. So dialing codes programmatically was not possible till iOS 10.

With the launch of iOS 11 Apple enabled developers to programmatically dial USSD code from iOS app with some limitations.


How to dial USSD code:                                                       

Use below piece of Swift code to invoke dialing of USSD codes

let ussdCode = "tel://{your_USSD_number}"

        let app = UIApplication.shared

        if let encoded = ussdCode.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {

            let u = encoded//"tel://\(encoded)"

            if let url = URL(string:u) {

                if app.canOpenURL(url) {

                    app.open(url, options: [:], completionHandler: { (finished) in

                        if finished{

                            //Do your stuff



When the above code gets executed, the app user will be shown a Dial prompt like below and will have to choose an action.

Note:  To dial USSD code with “#” you have to encode it like shown below else you will not get prompt for a number which contains “#”.

addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)


If you are interested to know about the status of this call you have made to dial USSD, check below

How to Track Ongoing Call Status:

We can track Dialled call status like call dialling, running, completed using callKit framework. CallKit is a new framework that aims to improve the VoIP experience by allowing apps to integrate tightly with the native Phone UI. CallKit has many functionalities that work with VoIP calling but here we are using it only to track dialed call status.

Implement Callkit in swift to check call status as follows:

Import required Library

import CallKit

Use Protocol and Delegate method :-

class viewController: UIViewController, CXCallObserverDelegate{

func callObserver(_ callObserver: CXCallObserver, callChanged call: CXCall) {

        if call.hasEnded == true {

            print("CXCallState :Ended")


        if call.isOutgoing == true && call.hasConnected == false {

            print("CXCallState :Dialing")


        if call.isOutgoing == false && call.hasConnected == false && call.hasEnded == false {

            print("CXCallState :Incoming")



        if call.hasConnected == true && call.hasEnded == false {

            print("CXCallState : Connected")




Thats it for now folks. Happy Coding!

FCM – send push notifications using Python

What is FCM ?

FCM – Firebase Cloud Messaging is a cross-platform  ( Android, iOS and Chrome ) messaging solution that lets you reliably deliver messages at no cost. FCM is best suited if you want to send push notification to your app which you built to run on Android and iOS. The advantage you get is you don’t have to separately deal with GCM (Google Cloud Messaging deprecated now) and Apple’s APNS. You hand over your notification message to FCM and FCM takes care of communicating with apple’s APNS and Android messaging servers to reliably deliver those messages.


Using FCM we can send message to single device or multiple devices.  There are two different types of messages, notification and data. Notification messages include JSON keys that are understood and interpreted by phone’s operating system. If you want to include customized app specific JSON keys use data message. You can combine both notification and data JSON objects in single message. You can also send messages with different priority.

Note : – You need to set priority  to high  if you want phone to wake up and show notification on screen

Sending message with Python

We can use PyFCM to send messages via FCM. PyFCM is good for synchronous ( blocking ) python. We will discuss non-blocking option in next paragraph.

Install PyFCM using following command

pip install pyfcm

The following code will send a push notification to

from pyfcm import FCMNotification

push_service = FCMNotification(api_key="<api-key>")

# OR initialize with proxies

proxy_dict = {
          "http"  : "",
          "https" : "",
push_service = FCMNotification(api_key="<api-key>", proxy_dict=proxy_dict)

# Your api-key can be gotten from:  https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging

registration_id = "<device registration_id>"
message_title = "Uber update"
message_body = "Hi john, your customized news for today is ready"
result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body)

print result
# Send to multiple devices by passing a list of ids.
registration_ids = ["<device registration_id 1>", "<device registration_id 2>", ...]
message_title = "Uber update"
message_body = "Hope you're having fun this weekend, don't forget to check today's news"
result = push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title, message_body=message_body)

print result

So, the PyFCM API is the pretty straight forward to use.

Sending FCM push notification using Twisted

PyFCM discussed in above paragraph is good enough if you want to send messages in blocking fashion. If you have to send high number of concurrent messages then using Twisted is a good option.

Twisted Matrix
Twisted Matrix

Network operations performed using twisted library don’t block. Thus it’s a good choice when network concurrency is required by program. We can use txFCM library to send FCM messages using twisted

Install txFCM using following command

pip install txfcm

Following code send FCM message using txFCM

from txfcm import TXFCMNotification
from twisted.internet import reactor

push_service = TXFCMNotification(api_key="<api-key>")

# Your api-key can be gotten from:  https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging
# Send to multiple devices by passing a list of ids.
registration_ids = ["<device registration_id 1>", "<device registration_id 2>", ...]
message_title = "Uber update"
message_body = "Hope you're having fun this weekend, don't forget to check today's news"
df = push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title, message_body=message_body)

def got_result(result):
    print result


txFCM is built on top of PyFCM so all the API call that are available in PyFCM are also available in txFCM.