如何为SimplePing提供警报?

时间:2018-05-26 09:26:50

标签: ios objective-c swift uiviewcontroller uialertcontroller

我有两个ViewControllers,一个是ViewController,另一个是GlobalViewController。我在GlobalVC中实现了SimplePing来检查网络连接。它工作正常,但我想在没有互联网的情况下显示警报。

这是我的代码,

//In ViewController.m
- (void)viewDidAppear:(BOOL)animated {
    //Calling SimplePing 'start' function
    [_gc checkNetConnection];    
}

//In GlobalVC
#pragma mark - SimplePingDelegate
- (void)simplePing:(SimplePing *)pinger didFailWithError:(NSError *)error {
    NSLog(@"didFailWithError: %@", [error description]);
    NSLog(@"#####%@", error.localizedDescription);

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"No internet connection, please check it..." preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
   [alert addAction:cancel];
   [alert addAction:ok];
   dispatch_async(dispatch_get_main_queue(), ^{
   [self presentViewController:alert animated:YES completion:nil];
   });
}

我收到此错误,

Warning: Attempt to present <UIAlertController: 0x146045800> on <GlobalViewController: 0x145e0e510> whose view is not in the window hierarchy!

其实这里我想发送当前的ViewController来呈现警报,但我不知道如何发送。

任何人都可以在Swift或Objective c中告诉我答案。

1 个答案:

答案 0 :(得分:0)

这种情况正在发生,因为您的GlobalViewController视图当前不存在于窗口中。当您导航到ViewController时,它已被替换。

如果您想在互联网不可用时在其他每个视图控制器中显示警报,您应该在UIViewController上将警报定义为类别,然后在您想要显示它时调用它。

这样的事情:

选择您的项目,然后按'Cmd + n'添加新文件。选择Objective-C File

new file

输入文件名并保存。

enter image description here

输入您的代码:

<强>的UIViewController + SimplePing.h

@interface UIViewController (SimplePing)
- (void)simplePing:(SimplePing *)pinger didFailWithError:(NSError *)error;
@end

<强>的UIViewController + SimplePing.m

@implementation UIViewController (SimplePing)
- (void)simplePing:(SimplePing *)pinger didFailWithError:(NSError *)error {
    NSLog(@"didFailWithError: %@", [error description]);
    NSLog(@"#####%@", error.localizedDescription);

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"No internet connection, please check it..." preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancel];
    [alert addAction:ok];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alert animated:YES completion:nil];
    });
}
@end

现在您可以从任何一个viewcontroller中调用它。