Monday, May 7, 2018

how to restrict mobile app access to only wifi

In enterprise application , the need for apps to use only wifi comes to picture sometimes as they can access intranet through wifi.

But with the advent of wifi-assist.It's possible sometimes Mobile data will be used for internet connectivity simultaneously along with wifi.

so how to stop this from happening so that app can use only wifi not mobile data.

allowscellularaccess property of NSMutableURLRequest solves the issue.

so if set this value to NO then if there is no wifi then it'll ignore the mobile data and return internet connect offline error message

Here is sample code to test

    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"https://www.google.com"]];    [request setAllowsCellularAccess:NO];    NSError *error;
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];        [request setHTTPMethod:@"GET"];
        NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"error:%@",error);
        NSLog(@"success:%@",response);
    }];
        [postDataTask resume];

Here is the sample error message we get


Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={NSUnderlyingError=0x1c004b700 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_kCFStreamErrorCodeKey=50, _kCFStreamErrorDomainKey=1}}, NSErrorFailingURLStringKey=https://www.google.com/, NSErrorFailingURLKey=https://www.google.com/, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=50, NSLocalizedDescription=The Internet connection appears to be offline.}

No comments:

Post a Comment