使用CTCallCenter(Swift)在iOS上检测电话 [英] Detect phone calls on iOS with CTCallCenter (Swift)

查看:325
本文介绍了使用CTCallCenter(Swift)在iOS上检测电话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试检测我的应用程序中的传入电话.我从头开始创建了一个新的Swift项目,只是为了尝试一些代码.我所做的唯一一件事就是在每个新项目创建的ViewController中导入CoreTelephony,而且我还将viewDidLoad()更改为:

I wanted to try to detect incoming phone calls in my app. I created a new Swift project from scratch just to try some code. The only thing I did was importing CoreTelephony in the ViewController that is created with every new project and I also changed the viewDidLoad() to:

    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let callCenter = CTCallCenter()
    NSLog("start")

    callCenter.callEventHandler = {[weak self] (call: CTCall) -> () in

        self?.label.text = call.callState
        NSLog("Call state")
        NSLog(call.callState)

    }

我还尝试了[弱自我],因为我是新手,并不知道这意味着什么.

I also tried without the [weak self] since I am new to swift and not sure of what it entails.

当我通过手机上的XCode运行我的新小应用程序时,接到呼叫,断开连接或其他任何事情都不会发生.没错,曾经如此.为了使用CoreTelephony框架和CTCallCenter,我还需要做更多的事情吗?

When I run my new little app via XCode on my phone nothing happens when a call is received, disconnected or anything else. No error what so ever. Do I have to do something more in order to use the CoreTelephony framework and the CTCallCenter?

问候 约翰

推荐答案

这是我上面评论的扩展.

This is an extension on my comment above.

尝试将callCenter设置为视图控制器的属性,而不仅仅是viewDidLoad中的变量.

Try making callCenter a property of your view controller instead of just a variable in viewDidLoad.

在方法中定义变量时,该变量及其值仅存在于该方法中.该方法完成运行后,将清除贵重物品及其值,以便它们不会继续使用内存(除非该值在其他地方使用).

When you define a variable in a method, the variable and it's value is only present within that method. When the method is finished running, the valuable and their values are clean up so they don't keep using memory (unless the value is used elsewhere).

在您的情况下,您定义callCenter并为其分配一个新的CTCallCenter实例.但是在viewDidLoad末尾,不再使用CTCallCenter实例,因此可以从内存中清除它.由于不再存在,因此无法处理通话事件.

In your case, you define callCenter and assign it a new CTCallCenter instance. But at the end of viewDidLoad, the CTCallCenter instance is not used anymore so it is clean up from memory. Since it no longer exists, it can't handle the call events.

通过添加callCenter作为视图控制器的属性,它将CTCallCenter实例的寿命与视图控制器的寿命联系起来.因此,仅当从内存中清除视图控制器时,才会从内存中清除CTCallCenter.

By adding callCenter as a property of your view controller, it ties the lifespan of the CTCallCenter instance to the lifespan of your view controller. So the CTCallCenter will only be clean up from memory when the view controller is cleaned up from memory.

有关更多详细信息,请阅读 Swift中的自动引用计数

For more detail, read Automatic Reference Counting in Swift

这篇关于使用CTCallCenter(Swift)在iOS上检测电话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆