iOS14獲取本地網(wǎng)絡(luò)權(quán)限思路

iOS14新增加本地網(wǎng)絡(luò)權(quán)限Privacy - Local Network Usage Description
如有本地網(wǎng)絡(luò)使用場景需要在info.plist中增加 Bonjour services字段(如投屏加入_leboremote._tcp

查看使用本地網(wǎng)絡(luò)的三方庫方法:在項目目錄下使用 grep -r SimplePing .命令即可

Apple官方無具體API查詢Local Network權(quán)限,這里采用建立定時器對本地網(wǎng)絡(luò)請求,如果請求不通則無Local Network權(quán)限。需要使用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(@"**可以使用局域網(wǎng)**");
    [self stop];
}

-  (void)simplePing:(SimplePing *)pinger didFailToSendPacket:(NSData *)packet sequenceNumber:(uint16_t)sequenceNumber error:(NSError *)error{
    if (error.code == 65) {
        [self stop];
        FF_DLog(@"**不可以使用局域網(wǎng)**");
        
        if (APPDELEAGTE.alertLocalNetView) {
            //申請權(quán)限不提示
            return;
        }
     }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容