How to use a function from the view controller in

2019-03-06 18:04发布

I have an app that is connected to a device by Bluetooth.

I want the app to send a command that indicates that the app is going to close in the app delegate method : (void)applicationWillTerminate:(UIApplication *)application {

2条回答
欢心
2楼-- · 2019-03-06 18:36

One word: NSNotificationCenter

I'm not sure what you need to set the data to because you can't pass the data seamlessly via NSNotificationCenter; however you were going to figure that out in your UIApplicationDelegate anyway, so why can't you do it in the view controller directly.

In your case there is no need to do anything in your application delegate, because this notification allows your view controller to act as a mini app delegate (in that you can get termination status and so on).

Therefore...

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TXdata:) name:UIApplicationWillTerminateNotification object:nil];
}

- (void)TXdata:(NSString *) data {
    NSString *newData = data;
    if (newData == nil) {
        newData = ... // Figure out what your data should be here.
    }
    //do whatever with your data here.
}

I quote:

UIApplicationWillTerminateNotification

Posted when the app is about to terminate.

This notification is associated with the delegate applicationWillTerminate: method. This notification does not contain a userInfo dictionary.

查看更多
【Aperson】
3楼-- · 2019-03-06 18:43

You should create a class separate from the view controller and app delegate to handle the BLE communication. That way, the view controller and the app delegate can both have access and provide a better "separation of concerns" for your app. This new class might work well as a singleton.

查看更多
登录 后发表回答