我是Swift的新手,我在networkExtension
内跟踪此方法的文档:
open class NEVPNConnection : NSObject {
/*!
* @method startVPNTunnelAndReturnError:
* @discussion This function is used to start the VPN tunnel using the current VPN configuration. The VPN tunnel connection process is started and this function returns immediately.
* @param error If the VPN tunnel was started successfully, this parameter is set to nil. Otherwise this parameter is set to the error that occurred. Possible errors include:
* 1. NEVPNErrorConfigurationInvalid
* 2. NEVPNErrorConfigurationDisabled
* @return YES if the VPN tunnel was started successfully, NO if an error occurred.
*/
@available(iOS 8.0, *)
open func startVPNTunnel() throws
我理解它的方式,如果它返回true,则建立VPN连接。
这是我的代码:
let result: Bool?
do {
result = try self.vpnManager.connection.startVPNTunnel()
if result! {
NotificationCenter.default.post(name: .enableDisconnect, object: nil)
}
} catch let error {
print("Error starting VPN Connection \(error.localizedDescription)");
}
但是在这一行:
result = try self.vpnManager.connection.startVPNTunnel()
我收到了这个错误:
无法指定类型'()'的值来输入'Bool?'
答案 0 :(得分:2)
文档涉及Objective-C方法。
Objective-C方法-(BOOL)doSomethingAndReturnError:(NSError *...
以doSomething() throws
的形式向Swift公开。
因此Swift方法没有返回值。你可以简单地写
do {
try self.vpnManager.connection.startVPNTunnel()
NotificationCenter.default.post(name: .enableDisconnect, object: nil)
} catch {
print("Error starting VPN Connection \(error.localizedDescription)");
}
但即使该方法返回Bool
在这种情况下从不使用可选项,请使用以下内容:
let result: Bool
do {
result = try doSomething()
} catch {
result = false
print("Error starting VPN Connection \(error.localizedDescription)");
}
if result {
NotificationCenter.default.post(name: .enableDisconnect, object: nil)
}
答案 1 :(得分:1)
函数startVPNTunnel
返回Void
。不是Bool
。试试这个:
do {
try self.vpnManager.connection.startVPNTunnel()
// If function reached that point startVPNTunnel didn't throw error
} catch let error {
// Some error
}