NetworkExtension connectOnDemand rules doesn't

2020-04-30 03:19发布

I have an app with VPN config created by the new NetworkExtension framework. It works just fine, but now I need to add some rules to turn this VPN only when I'm trying to connect to a specific URL. I planed to use NEVPNManager's connectOnDemand feature, but it does`t seem to be working for me. When I'm opening http://some-site.com in safari my VPN connection should establish, but for some reason it does't. I tried a different type of configurations as well as using generated .mobileconfig files to make connectOnDemand work, but with no luck. Whats wrong with it? I'm testing on code like this:

let manager = NEVPNManager.sharedManager()

manager.enabled = true

manager.loadFromPreferencesWithCompletionHandler { (err) -> Void in
    manager.removeFromPreferencesWithCompletionHandler { (err0) -> Void in
                print("err0 \(err0)")
                print("err \(err)")
                let config = NEVPNProtocolIPSec()
                config.localIdentifier = "NEVPNProtocolIPSec"
                config.remoteIdentifier = "NEVPNProtocolIPSecRemote"
                config.disconnectOnSleep = true
                config.serverAddress = server
                config.authenticationMethod = .Certificate
                //configurating here
                manager.protocolConfiguration = config
                let onDemandRule1 = NEOnDemandRuleConnect()
                onDemandRule1.DNSSearchDomainMatch = ["some-site.com", "*.some-site.com"]

                manager.onDemandRules = [onDemandRule1]
                manager.onDemandEnabled = true
                manager.saveToPreferencesWithCompletionHandler({ (err2) -> Void in
                    print("err2 \(err2)")
                })
            }
        }

2条回答
做个烂人
2楼-- · 2020-04-30 03:29

You need to add the line

manager.onDemandEnabled = true
查看更多
Anthone
3楼-- · 2020-04-30 03:40

I made it work with the next rules:

let onDemandRule = NEOnDemandRuleEvaluateConnection()
let evaluateRule = NEEvaluateConnectionRule(matchDomains: ["*.some-site.com"], andAction: .ConnectIfNeeded)
evaluateRule.probeURL = NSURL(string: "https://a.url.accecable.only.from.vpn")

onDemandRule.connectionRules = [evaluateRule]
manager.protocolConfiguration = config
manager.onDemandRules = [onDemandRule]
查看更多
登录 后发表回答