iOS14获取本地网络权限思路

iOS14新增加本地网络权限Privacy - Local Network Usage Description
如有本地网络使用场景需要在info.plist中增加 Bonjour services字段(如投屏加入_leboremote._tcp

查看使用本地网络的三方库方法:在项目目录下使用 grep -r SimplePing .命令即可

Apple官方无具体API查询Local Network权限,这里采用建立定时器对本地网络请求,如果请求不通则无Local Network权限。需要使用Ping库(https://github.com/yluo8090/Common/tree/main/Ping)具体见下:

#import "SimplePing.h"
#import "LDSRouterInfo.h"

@interface LocalNetManager ()<SimplePingDelegate>
{
    dispatch_source_t _timer;
}
@property (nonatomic, strong) SimplePing *pinger;
@end
- (void)stop{
    if (_pinger) {
        [_pinger stop];
    }

    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

- (void)checkLocalNetStatus{
    NSDictionary *router = [LDSRouterInfo getRouterInfo];
    _pinger = [[SimplePing alloc] initWithHostName:router[@"ip"]];
    _pinger.delegate = self;
    [_pinger start];
}

- (void)simplePing:(SimplePing *)pinger didStartWithAddress:(NSData *)address{
    if (_timer) {
        return;
    }
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_timer, ^{
        [pinger sendPingWithData:nil];
    });
    dispatch_resume(_timer);
}

- (void)simplePing:(SimplePing *)pinger didSendPacket:(NSData *)packet sequenceNumber:(uint16_t)sequenceNumber{
    FF_DLog(@"**可以使用局域网**");
    [self stop];
}

-  (void)simplePing:(SimplePing *)pinger didFailToSendPacket:(NSData *)packet sequenceNumber:(uint16_t)sequenceNumber error:(NSError *)error{
    if (error.code == 65) {
        [self stop];
        FF_DLog(@"**不可以使用局域网**");
        
        if (APPDELEAGTE.alertLocalNetView) {
            //申请权限不提示
            return;
        }
     }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容