簡體   English   中英

當用戶按下主頁按鈕時如何編寫不會暫停的代碼

[英]How to write code that will not pause when user press home button

我想在我的ios應用中實現圖像同步。 為此,我所做的是

  1. 拍個照
  2. 將該照片上傳到firebase
  3. 獲取Firebase存儲的url並將其發送到api服務器,以便服務器將該信息存儲到數據庫

只要應用程序正在運行,它就可以正常工作,但是當我退出應用程序並按“主頁”按鈕時,所有內容都會暫停。

那么,如何運行在應用程序進入首頁時不會暫停的代碼?

根據本文檔,

對於需要更多執行時間才能實現的任務,您必須請求特定的權限才能在后台運行它們而不暫停它們。 在iOS中,只允許特定的應用類型在后台運行:

  • 在后台播放用戶可聽內容的應用程序,例如音樂播放器應用程序

  • 在后台記錄音頻內容的應用程序,使用戶始終了解其位置的應用程序,例如導航應用程序

  • 支持互聯網協議語音(VoIP)的應用程序需要定期下載和處理新內容的應用程序

  • 從外部配件接收定期更新的應用

  • 實現這些服務的應用必須聲明它們支持的服務,並使用系統框架來實現這些服務的相關方面

聲明服務可以使系統知道您使用的服務,但是在某些情況下,實際上是系統框架阻止了應用程序被掛起。

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

這是實現方法(摘自Ashley 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) } 

[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 ,因此不確定完成此操作的最長時間是多少

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM