2017-03-08 63 views
0

我想在我的ios应用程序中实现图像同步。这就是我所做的是如何编写在用户按主页按钮时不会暂停的代码

  1. 拍照
  2. 上传照片火力
  3. 得到火力存储网址,并将其发送到API服务器,使服务器存储信息的数据库

只要应用程序正在运行,它就可以正常工作,但是当我按下主屏幕按钮退出应用程序时,所有事件都会暂停。

那么如何运行一个代码,不会暂停,如果应用程序进入主页?

回答

1

按照这个文件,

对于需要更多的执行时间来实现的任务,必须 要求特定权限在后台运行它们,而不 他们被暂停。在iOS中,只有特定的应用程序类型允许 在后台运行:

  • 应用程式播放音频内容给用户,而在后台, 如音乐播放器应用程序

  • 应用该记录的音频内容,而在告诉用户他们的位置在所有 倍,S的 后台应用UCH作为导航的应用程序,支持互联网语音 协议(VoIP)

  • 应用程序需要下载和处理新的内容 定期

  • 接收定期更新

    Apps的应用来自外部配件

  • 应用实现这些服务必须申报服务,他们 支持和使用的系统框架,以执行的 相关方面的服务

声明的服务让系统知道你使用的 服务,但在某些情况下,实际上会阻止您的应用程序被挂起的系统框架。

链接:https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

这里是如何实现(从this answerAshley Mills拍摄):

func doUpdate() { 

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { 

    let taskID = beginBackgroundUpdateTask() 

    var response: NSURLResponse?, error: NSError?, request: NSURLRequest? 

    let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) 

    // Do something with the result 

    endBackgroundUpdateTask(taskID) 

    }) 
} 

func beginBackgroundUpdateTask() -> UIBackgroundTaskIdentifier { 
    return UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({}) 
} 

func endBackgroundUpdateTask(taskID: UIBackgroundTaskIdentifier) { 
    UIApplication.sharedApplication().endBackgroundTask(taskID) 
} 
+0

得到错误与迅速3.可以ü请更新答案 – Mahabub

+0

不幸的是,我没有经验与迅速编程。上面的代码是从SO上的答案引用的。 –

0

[Swift3]这是一种工作对我来说

func doUpdate() { 
    DispatchQueue.global(qos: .background).async { 
     let taskID = self.beginBackgroundUpdateTask() 
     DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5), execute: { 
      print("printing after 10 min") 
     }) 
     DispatchQueue.main.async { 
      self.endBackgroundUpdateTask(taskID: taskID) 
     } 
    } 
} 


func beginBackgroundUpdateTask() -> UIBackgroundTaskIdentifier { 
    return UIApplication.shared.beginBackgroundTask(expirationHandler: {}) 
} 


func endBackgroundUpdateTask(taskID: UIBackgroundTaskIdentifier) { 
    UIApplication.shared.endBackgroundTask(taskID) 
} 

不知道这是完成最大时间是什么,因为我看到有一个expirationHandler

+1

根据本教程,https://www.raywenderlich.com/143128/background-modes-tutorial-getting-started,在过去,这种模式通常用于完成上传或下载,并且慷慨(但不能保证)提供了10分钟来完成这些任务。 –

相关问题