Reputation: 21
I want to develop VPN on iOS By PacketTunnel,But when I run this code ,it will return a error message "The operation couldn’t be completed. (NEVPNErrorDomain error 2.)". This error code can't be found,Does any one know this reason?
Here is my objective-c code: -(void)Loadvpn{
[NETunnelProviderManager loadAllFromPreferencesWithCompletionHandler:^(NSArray<NETunnelProviderManager*>
* _Nullable managers, NSError * _Nullable error) {
if (error) {
DLog("%@",error.localizedDescription)
}else{
if([managers count]==0){
DLog("no conf,to add a conf")
NETunnelProviderManager *man = [[NETunnelProviderManager alloc] init];
NETunnelProviderProtocol *protocol = [[NETunnelProviderProtocol alloc] init];
// bundle ID of tunnel provider
protocol.providerBundleIdentifier = @"com.xxxx.netp.";
protocol.providerConfiguration = @{@"key1": @"value"};
protocol.passwordReference = [STKeyChain searchKeychainCopyMatching:@"123"];
protocol.serverAddress = @"192.168.1.106"; // VPN server address
man.protocolConfiguration=protocol;
man.localizedDescription = @"linly vt";
man.onDemandEnabled = false;
[man saveToPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
if(error){
DLog("%@",error.description);
}else{
[man loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
if(error){
DLog("load2nd %@",error.description);
}
DLog("add success");
DLog("now status:%ld",man.connection.status);
[self StartConnect:man];
}];
}
}];
} else{
DLog("existed conf,%@",managers[0])
[managers[0] loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
if(error){
DLog("load2nd %@",error.description);
}
DLog("now status:%ld",managers[0].connection.status);
[self StartConnect:managers[0]];
}];
}
}
}];
}
-(void)StartConnect:(NETunnelProviderManager*)man{ DLog("start to connect");
NETunnelProviderSession *session = (NETunnelProviderSession*)man.connection;
NSDictionary *options = @{@"key" : @"value"}; // Send additional options to the tunnel provider
NSError *err;
[session startTunnelWithOptions:options andReturnError:&err];
DLog("%@,%@",err.localizedDescription,err.localizedFailureReason);
}
Upvotes: 2
Views: 1961
Reputation: 41
You need to enable manager before start tunnel. I recommend that you add code like this before saveToPreferences.
NETunnelProviderManager *man = [[NETunnelProviderManager alloc] init];
NETunnelProviderProtocol *protocol = [[NETunnelProviderProtocol alloc] init];
// bundle ID of tunnel provider
protocol.providerBundleIdentifier = @"com.xxxx.netp.";
protocol.providerConfiguration = @{@"key1": @"value"};
protocol.passwordReference = [STKeyChain searchKeychainCopyMatching:@"123"];
protocol.serverAddress = @"192.168.1.106"; // VPN server address
man.protocolConfiguration=protocol;
man.localizedDescription = @"linly vt";
man.onDemandEnabled = false;
//Noteice this line
man.enabled = YES;
[man saveToPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
Upvotes: 4