对于尚未找到从App Extension(Widget)实现调用功能或按钮点击的方法的人:
注意:这是使用 Swift
注意 2:将 NSNotification 和方法的名称替换为您的实现
- 首先,创建 NotificationCenter post 方法(在 Swift 2.0 - NSNotification Center 中)
在 App Delegate 类中创建方法 -
var scheme: String!
var host: String!
然后,在类的底部(最后一个之后)添加以下函数:
func application(_ app: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
scheme = url.scheme
host = url.host
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NOTIFICATION_NAME"), object: nil)
return true
}
-
在您的 ViewController 类中,您希望通过单击 Widget 执行函数或语句,在 super.viewDidLoad() 中添加以下内容:
NotificationCenter.default.addObserver(self,selector: #selector(self.YOUR_METHOD_NAME),
name: NSNotification.Name(rawValue: "NOTIFICATION_NAME"),
object: nil)
以及你要调用的方法:
func YOUR_METHOD_NAME(notification: NSNotification) {
let appDelegate =
UIApplication.shared.delegate as! AppDelegate
if appDelegate.scheme != nil {
startRecording()
}
}
-
我假设您已经创建了小部件目标及其视图。将此添加到 TodayViewController 中您要处理点击的按钮:
@IBAction func openApp(_ sender: UIButton) {
openApp()
}
以及通过 URl Scheme 处理打开应用程序的功能:
func openApp(){
let myAppUrl = NSURL(string: "YOUR_URL_SCHEME://YOUR_HOST_NAME")!
extensionContext?.open(myAppUrl as URL, completionHandler: { (success) in
if (!success) {
self.textView.text = "There was a problem opening app!"
}
})
}
对于 YOUR_URL_SCHEME,添加您在 Info.plist 中指定的方案,如果没有,请转到此链接并按照说明操作:
Add URL Scheme to Xcode
对于 YOUR_HOST_NAME,您可以删除它,并且只能通过 URL Scheme 打开应用程序。
编码愉快!