Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用iOS后台模式?_Ios_Iphone_Swift_Background_Swift2 - Fatal编程技术网

如何使用iOS后台模式?

如何使用iOS后台模式?,ios,iphone,swift,background,swift2,Ios,Iphone,Swift,Background,Swift2,我想为iPhone创建一个类似WhatsApp和Viber(可能是Skype)的应用程序,从iOS 8.4开始,使用swift 2.2。因此,我需要每隔30秒向我的服务器发送https请求(我使用的是'NSURLSession'),以表明我的应用程序处于联机状态,其他联系人可以看到它。若应用程序处于活动状态,那个么它是并没有问题的,定时器工作正常,每30秒一次。但我需要应用程序在非活动、后台、暂停和不运行(如果可能的话)模式下工作,即使iPhone正在睡眠。我只需要发出一点信号,仅此而已。 我已

我想为iPhone创建一个类似WhatsApp和Viber(可能是Skype)的应用程序,从iOS 8.4开始,使用swift 2.2。因此,我需要每隔30秒向我的服务器发送https请求(我使用的是'NSURLSession'),以表明我的应用程序处于联机状态,其他联系人可以看到它。若应用程序处于活动状态,那个么它是并没有问题的,定时器工作正常,每30秒一次。但我需要应用程序在非活动、后台、暂停和不运行(如果可能的话)模式下工作,即使iPhone正在睡眠。我只需要发出一点信号,仅此而已。 我已经有了这个代码:

func registerBackgroundTask() {
    backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler {
        [unowned self] in self.endBackgroundTask()
    }
    assert(backgroundTask != UIBackgroundTaskInvalid)
}

func endBackgroundTask() {
    UIApplication.sharedApplication().endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
}

func reinstateBackgroundTask() {
    if backgroundTask == UIBackgroundTaskInvalid {
        registerBackgroundTask()
    }
}

func functionToPerformOnBackground() {
    requestToServer()
}
此函数由AppDelegate.swift中的计时器调用,如下所示:

func applicationDidEnterBackground(application: UIApplication) {

    //START BACKGROUND TIMER!!!
    if !timerForBackgroundRunning {
        timerForBackground = NSTimer.scheduledTimerWithTimeInterval(20, target: self, selector: "functionToPerformOnBackground", userInfo: nil, repeats: true)
        registerBackgroundTask()
        timerForBackgroundRunning = true            
    }
}

这段代码工作得很好,但当iPhone进入睡眠状态时,它会停止发送请求。为了再次强制代码工作,我必须再次进入应用程序,然后按下iPhone上的Home按钮。我已经测试过Viber和WhatsApp,我可以说WhatsApp的工作原理类似,但Viber知道如何解决这个问题。 谁能帮帮我吗? 我将感谢任何帮助、建议或任何事情。 另外,我已经看过本教程:
很好,但还不完整。

你读过应用程序编程指南中的“实现VoIP应用程序”一节吗?呵呵,我没有。原因:它非常大,它使用目标C,这是相当困难的。如果我读它会对我有帮助吗?我是说,我的问题有解决办法吗?谢谢你的回复!是的,它会帮助你的。苹果在iOS中为VoIP应用程序做出了具体的调整,该文件描述了它们是什么。谁说写应用程序应该很容易?不,不容易,但是,我想,没有额外的复杂性。事实上,我不使用VoIP,因为这个部分是为我制作的,就像是附加的库,它是用C++编写的,我没有代码。所以我只需要发送请求。。。
func applicationDidBecomeActive(application: UIApplication) {
    if timerForBackgroundRunning {
        timerForBackground.invalidate()
        if backgroundTask != UIBackgroundTaskInvalid {
            endBackgroundTask()
        }
        timerForBackgroundRunning = false
    }
}