iOS 请求本地网络权限状态
短信预约 -IT技能 免费直播动态提醒
//// KdLocalNetworkManager.swift// //// Created by bob bob on 2023/4/13.//import Foundationimport Network/// Uses bonjour networking to relialby check if user has granted local network access/// How to use:/// Add LocalNetworkAuthorization class to your project/// Open .plist file and add "_bonjour._tcp", "_lnp._tcp.", as a values under "Bonjour services"/// Call requestAuthorization() to trigger the prompt or get the authorization status if it already been approved/denied/// about the author: https://stackoverflow.com/a/67758105/705761public class KdLocalNetworkManager: NSObject { private var browser: NWBrowser? private var netService: NetService? private var completion: ((Bool) -> Void)? public func requestAuthorization() async -> Bool { return await withCheckedContinuation { continuation in requestAuthorization() { result in continuation.resume(returning: result) } } } private func requestAuthorization(completion: @escaping (Bool) -> Void) { self.completion = completion // Create parameters, and allow browsing over peer-to-peer link. let parameters = NWParameters() parameters.includePeerToPeer = true // Browse for a custom service type. let browser = NWBrowser(for: .bonjour(type: "_bonjour._tcp", domain: nil), using: parameters) self.browser = browser browser.stateUpdateHandler = { newState in switch newState { case .failed(let error): print(error.localizedDescription) case .ready: break case .cancelled: break case let .waiting(error): print("Local network permission has been denied: \(error)") self.reset() self.completion?(false) default: break } } self.netService = NetService(domain: "local.", type:"_lnp._tcp.", name: "LocalNetworkPrivacy", port: 1100) self.netService?.delegate = self self.browser?.start(queue: .main) self.netService?.publish() } private func reset() { self.browser?.cancel() self.browser = nil self.netService?.stop() self.netService = nil }}extension KdLocalNetworkManager : NetServiceDelegate { public func netServiceDidPublish(_ sender: NetService) { self.reset() print("Local network permission has been granted") completion?(true) }}
1 在 .plist 添加"_bonjour._tcp", “_lnp._tcp.”, 到 “Bonjour services”
2 使用,只有被拒绝时候才会回调回来
Task.init { do{ let isOK = try await KdLocalNetworkManager().requestAuthorization() print("ok") if(!isOK){ let settingStrUrl = UIApplication.openSettingsURLString//"App-Prefs:root=Bluetooth" let alertStr = NSLocalizedString("请打开本地网络权限", comment: "") let url = URL(string: settingStrUrl) guard let url = url else{return } if(UIApplication.shared.canOpenURL(url)){UIApplication.shared.open(url) } } }catch{ print("exception") } }
来源地址:https://blog.csdn.net/bobbob32/article/details/131106416
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341