How to return BOOL when checking internet connection in XCODE

前端 未结 4 1109
自闭症患者
自闭症患者 2021-01-23 03:52

I want to be able to check for internet connectivity when my View loads. To predetermine the contents of my view.

I have the following viewDidLoad method:



        
4条回答
  •  北恋
    北恋 (楼主)
    2021-01-23 04:04

    Yo can respect the asynchronicity in the implementation and modify the signature of the method to accept a block too.

    First you typedef your new block in the header

    typedef void(^ReachabilityCompletionBlock)(BOOL reachable);
    

    then

    - (void)isInternetReachable:(ReachabilityCompletionBlock)paramReachabilityBlock
    {
        NSLog(@"Starting connection test");
    
        internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];
    
        // Internet is reachable
        internetReachableFoo.reachableBlock = ^(Reachability*reach){
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"We have internet");
            paramReachabilityBlock(YES); 
            });
        };
    
        // Internet is not reachable
        internetReachableFoo.unreachableBlock = ^(Reachability*reach){
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"We do not have internet");
            paramReachabilityBlock(NO);
            });
        };
    
        [internetReachableFoo startNotifier];
    }
    

提交回复
热议问题