Find if the user is on a call or not?

I wanted to know if the user was using the app and see if they were in a phone call or not. I followed this link to check if the user was in a phone call or not: iOS. How to check if a phone call is actually in use . However, it looks like Objective-C. I was wondering if there is a Swift equivalent for this. This is my attempt:

    var currCall = CTCallCenter()
    var call = CTCall()

    for call in currCall.currentCalls{
        if call.callState == CTCallStateConnected{
            println("In call.")
        }
    }

      

However, it looks like the call has an attribute .callState

as in the previous example. Any help would be appreciated! Thank!

+4


source to share


3 answers


Update for Swift 2.2: You just need to unzip safely currCall.currentCalls

.

import CoreTelephony
let currCall = CTCallCenter()

if let calls = currCall.currentCalls {
    for call in calls {
        if call.callState == CTCallStateConnected {
            print("In call.")
        }
    }
}

      




Previous answer: you need to safely unpack and tell what type it is, the compiler doesn't know.

import CoreTelephony
let currCall = CTCallCenter()

if let calls = currCall.currentCalls as? Set<CTCall> {
    for call in calls {
        if call.callState == CTCallStateConnected {
            println("In call.")
        }
    }
}

      

+5


source


iOS 10, Swift 3



import CallKit

/**
    Returns whether or not the user is on a phone call
*/
private func isOnPhoneCall() -> Bool {
    for call in CXCallObserver().calls {
        if call.hasEnded == false {
            return true
        }
    }
    return false
}

      

+9


source


Or shorter (swift 5.1):

private var isOnPhoneCall: Bool {
    return CXCallObserver().calls.contains { $0.hasEnded == false }
}

      

0


source







All Articles