首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >WatchKit扩展后台刷新的Apple示例代码

WatchKit扩展后台刷新的Apple示例代码
EN

Stack Overflow用户
提问于 2017-09-07 09:30:13
回答 1查看 4.8K关注 0票数 25

我已经寻找这个问题的答案很长一段时间了,所以我想我愿意冒着一些失败的风险来发布它。

基本上,我想让Apple提供的用于Apple Watch后台刷新的示例代码实际工作(链接和代码如下)。

我在模拟器和苹果手表系列2的iPhone 6s上都试过了,后台任务从来没有成功完成到时间更新的地步。我尝试将手表应用程序固定在码头上,并尝试将应用程序保持在前台并将其发送到后台,无论是在模拟器中还是在实际的手表上。我甚至试着等了将近一年,看看Xcode或Apple Watch是否会收到更新,让它正常工作。

有没有人成功地修改了Apple提供的代码,使其正常工作?

您可以在此处下载整个runnable示例项目:WatchBackgroundRefresh: Using WKRefreshBackgroundTask to update WatchKit apps in the background

代码语言:javascript
复制
 /*
 Copyright (C) 2016-2017 Apple Inc. All Rights Reserved.
 See LICENSE.txt for this sample’s licensing information

 Abstract:
 The main interface controller.
 */

import WatchKit
import Foundation


class MainInterfaceController: WKInterfaceController, WKExtensionDelegate, URLSessionDownloadDelegate {
    // MARK: Properties

    let sampleDownloadURL = URL(string: "http://devstreaming.apple.com/videos/wwdc/2015/802mpzd3nzovlygpbg/802/802_designing_for_apple_watch.pdf?dl=1")!

    @IBOutlet var timeDisplayLabel: WKInterfaceLabel!

    private let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .none
        formatter.timeStyle = .long

        return formatter
    }()

    // MARK: WKInterfaceController

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        // Configure interface objects here.
        WKExtension.shared().delegate = self
        updateDateLabel()
    }

    // MARK: WKExtensionDelegate
    func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
        for task : WKRefreshBackgroundTask in backgroundTasks {
            print("received background task: ", task)
            // only handle these while running in the background
            if (WKExtension.shared().applicationState == .background) {
                if task is WKApplicationRefreshBackgroundTask {
                    // this task is completed below, our app will then suspend while the download session runs
                    print("application task received, start URL session")
                    scheduleURLSession()
                }
            }
            else if let urlTask = task as? WKURLSessionRefreshBackgroundTask {
                let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: urlTask.sessionIdentifier)
                let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)

                print("Rejoining session ", backgroundSession)
            }
            // make sure to complete all tasks, even ones you don't handle
            task.setTaskCompleted()
        }
    }

    // MARK: Snapshot and UI updating

    func scheduleSnapshot() {
        // fire now, we're ready
        let fireDate = Date()
        WKExtension.shared().scheduleSnapshotRefresh(withPreferredDate: fireDate, userInfo: nil) { error in
            if (error == nil) {
                print("successfully scheduled snapshot.  All background work completed.")
            }
        }
    }

    func updateDateLabel() {
        let currentDate = Date()
        timeDisplayLabel.setText(dateFormatter.string(from: currentDate))
    }

    // MARK: URLSession handling

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        print("NSURLSession finished to url: ", location)
        updateDateLabel()
        scheduleSnapshot()
    }

    func scheduleURLSession() {
        let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: NSUUID().uuidString)
        backgroundConfigObject.sessionSendsLaunchEvents = true
        let backgroundSession = URLSession(configuration: backgroundConfigObject)

        let downloadTask = backgroundSession.downloadTask(with: sampleDownloadURL)
        downloadTask.resume()
    }

    // MARK: IB actions

    @IBAction func ScheduleRefreshButtonTapped() {
        // fire in 20 seconds
        let fireDate = Date(timeIntervalSinceNow: 20.0)
        // optional, any SecureCoding compliant data can be passed here
        let userInfo = ["reason" : "background update"] as NSDictionary

        WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: fireDate, userInfo: userInfo) { (error) in
            if (error == nil) {
                print("successfully scheduled background task, use the crown to send the app to the background and wait for handle:BackgroundTasks to fire.")
            }
        }
    }

}

以下是在模拟器上运行时的输出。在其他配置中运行时输出相似(但不一定完全相同):

代码语言:javascript
复制
successfully scheduled background task, use the crown to send the app to the background and wait for handle:BackgroundTasks to fire.
received background task:  <WKSnapshotRefreshBackgroundTask: 0x7b019030>
received background task:  <WKApplicationRefreshBackgroundTask: 0x7a711290>
application task received, start URL session
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46086536

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档