iOS 开发:判断网络权限并自动发起请求 (OC 代码)
可以使用 Reachability 来判断网络权限是否打开。以下是一个示例代码:
首先,在你的工程中导入 Reachability 库。可以从官方 Github 地址下载:https://github.com/tonymillion/Reachability
然后,在你的代码中使用以下代码判断网络权限是否打开:
#import "Reachability.h"
- (BOOL)isNetworkAvailable {
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
if (networkStatus == NotReachable) {
return NO;
}
return YES;
}
在发起网络请求之前,可以调用isNetworkAvailable方法判断网络权限是否打开。如果返回 YES,表示网络权限已打开,可以发起网络请求;如果返回 NO,表示网络权限未打开,需要提示用户打开网络权限。
发起网络请求的代码示例:
NSURL *url = [NSURL URLWithString:'https://www.example.com'];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// 处理网络请求的结果
}];
[dataTask resume];
以上代码使用 NSURLSession 发起网络请求,并在请求完成后的 completionHandler 中处理请求的结果。请根据你的具体需求进行相应的修改。
原文地址: https://www.cveoy.top/t/topic/ffpG 著作权归作者所有。请勿转载和采集!