Perform action in host app from Today extension(Widget) Without opening app ios

后端 未结 2 1315
感动是毒
感动是毒 2021-01-01 15:28

I want to manage some action in containing app from today extension(Widget).

Full description: in my containing app, some action (like play/pause audio) perform. An

2条回答
  •  清酒与你
    2021-01-01 16:06

    Use MMWormhole (or its new and unofficial Swift version, just Wormhole). It's very simple.

    In the app's view controller:

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let wormhole = MMWormhole(applicationGroupIdentifier: "group.test.TodayExtensionSharingDefaults",
                                  optionalDirectory: "TodayExtensionSharingDefaults")
    
        wormhole.listenForMessage(withIdentifier: "togglePlayPause") { [weak self] _ in
            guard let controller = self else { return }
            controller.btnValue.isSelected = controller.btnValue.isSelected
        }
    }
    

    In the extension:

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view from its nib.
    
        self.wormhole = MMWormhole(applicationGroupIdentifier: "group.test.TodayExtensionSharingDefaults", optionalDirectory: "TodayExtensionSharingDefaults")
    }
    
    @IBAction func onPlayPause(_ sender: UIButton) {
        guard let wormhole = self.wormhole else { extensionContext?.openURL(NSURL(string: "foo://startPlaying")!, completionHandler: nil) } // Throw error here instead of return, since somehow this function was called before viewDidLoad (or something else went horribly wrong)
    
        wormhole.passMessageObject(nil, identifier: "togglePlayPause")
    }
    

    Declare foo:// (or whatever else you use) in Xcode's Document Types section, under URLs, then implement application(_:open:options:) in your AppDelegate so that the app starts playing music when the URL passed is foo://startPlaying.

提交回复
热议问题