У меня есть два ViewController, один - ViewController, а другой - GlobalViewController. Я реализовал SimplePing в GlobalVC для проверки сетевого соединения. Он работает нормально, но я хочу показывать предупреждение, когда «нет интернета».
Это мой код,
//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.





Это происходит потому, что ваше представление GlobalViewController в настоящее время отсутствует в окне. Он был заменен, когда вы перешли к ViewController.
Если вы хотите отображать свое предупреждение в любом другом контроллере просмотра, когда Интернет недоступен, вы должны определить предупреждение как категорию в UIViewController, а затем вызывать его всякий раз, когда вы хотите его отобразить.
Что-то вроде этого:
Выберите проект и нажмите «Cmd + n», чтобы добавить новый файл. Выберите файл Objective-C
Введите имя файла и сохраните.
Введите ваш код:
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
Теперь вы можете вызвать его из любого контроллера просмотра.
Конечно. Выберите свой проект, нажмите cmd + n, чтобы добавить новый файл. Выберите «Файл Objective-C» в меню iOS. Затем выберите «Категория» в типе файла, выберите «UIViewController» в классе и введите имя файла.
@iOS Я обновил ответ, чтобы рассказать, как добавить категорию.
@ HAK, не отображается предупреждение ... Возникает такая же проблема. Большое спасибо за ответ.
В ViewController Imported> h файл и - (void) viewDidAppear: (BOOL) анимированный {UIViewController * vc = [[UIViewController alloc] init]; [предупреждение vc]; }
@iOS Представьте это в viewDidAppear следующим образом: [самооповещение];
Позвольте нам продолжить обсуждение в чате.
Подскажите, пожалуйста, как создавать файлы UIViewController + SimplePing.h / .m