Vpn on demand in ios 9.2 - ios

I want to use VPN on Demand feature that is available in Network Extension framework,I want to connect the VPN when the specific URL or site is open in the browser.
For Example: when I write www.google.com my VPN will be connected and not on any other sites.
After a lot of searching on internet,I tried the following code
NEVPNManager *manager = [NEVPNManager sharedManager];
[manager loadFromPreferencesWithCompletionHandler:^(NSError *error) {
if(error) {
NSLog(#"Load error: %#", error);
} else {
NEVPNProtocolIKEv2 *p = [[NEVPNProtocolIKEv2 alloc] init];
p.username = #"Username";
p.passwordReference = [res objectForKey:#"v_PersistentRef"];
p.serverAddress = strAddress;
p.authenticationMethod = NEVPNIKEAuthenticationMethodCertificate;
p.serverCertificateIssuerCommonName = #"COMODO RSA Domain Validation Secure Server CA";
p.serverCertificateCommonName =strAddress;
p.identityData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"point-to-client2" ofType:#"p12"]];
p.identityDataPassword = #"vpnuser";
p.localIdentifier = strAddress;
p.remoteIdentifier = strAddress;
p.useExtendedAuthentication = YES;
p.disconnectOnSleep = NO;
[manager setProtocol:p];
NSLog(#"password: %#", [manager protocol].passwordReference);
[manager setOnDemandEnabled:YES];
[manager setEnabled:YES];
Then setting the onDemandRules by the following code:
NEEvaluateConnectionRule * ru = [[NEEvaluateConnectionRule alloc] initWithMatchDomains:#[#"google.com"] andAction:NEEvaluateConnectionRuleActionConnectIfNeeded];
ru.probeURL = [[NSURL alloc] initWithString:#"http://www.google.com"];
NSArray *arr = [[NSArray alloc] initWithObjects:ru, nil];
NEOnDemandRuleEvaluateConnection *ec =[[NEOnDemandRuleEvaluateConnection alloc] init];
ec.interfaceTypeMatch = 2;
[ec setConnectionRules:arr];
NSArray *arr2 = [[NSArray alloc] initWithObjects:ec, nil];
NSLog(#"onDemandRules: %#", arr2);
//
[manager setOnDemandRules:arr2];
[manager setLocalizedDescription:#"VPN Profile"];
[manager saveToPreferencesWithCompletionHandler:^(NSError *error) {
if(error) {
NSLog(#"Save error: %#", error);
}
else {
NSLog(#"Saved");
}
Here the VPN configuration profile is updated and then start VPN connection through the following code:
NSError *startError;
[[NEVPNManager sharedManager].connection startVPNTunnelAndReturnError:&startError];
if(startError) {
NSLog(#"Start error: %#", startError.localizedDescription);
} else {
NSLog(#"Connection established!");
}
Now I faced the following problems:
1)When the profile is updated the ondemand feature is not working as when I write in the browser Url i.e www.google.com,the vpn is not connected.So I cannot understand what I did wrong in the code ?
2)How to give the dynamic domain or url like what I placed in the initWithMatchDomains:#[#"google.com"] or in the probeUrl that will be workable for google.com as well as google.de or any google domain??
I know its quite a long and detailed question but I really want help.
Any help will be highly appreciated.
Thanks

Ok,I am going to answer my question as I almost solve the problem.
The On demand Vpn feature is perfectly working as I did a slightly modified the code as follows:
I just made an array for the domain
NSArray *arrDomains =[[NSArray alloc] initWithObjects:#"youtube.com","google.com",nil];
Then Evaluate the connection rule
NEEvaluateConnectionRule * ru = [[NEEvaluateConnectionRule alloc] initWithMatchDomains:arrDomains andAction:NEEvaluateConnectionRuleActionConnectIfNeeded];
Then using the property
ru.useDNSServers = arrDomains;
Then the remaining code is same as above mentioned in the question.
NSArray *arrRules = [[NSArray alloc] initWithObjects:ru,nil];
NEOnDemandRuleEvaluateConnection *ec = [[NEOnDemandRuleEvaluateConnection alloc] init];
ec.interfaceTypeMatch = 2;
[ec setConnectionRules:arrRules];
NSArray *arr2 = [[NSArray alloc] initWithObjects:ec, nil];
NSLog(#"onDemandRules: %#", arr2);
[manager setOnDemandRules:arr2];
The above code can create vpn connection on the domains defined in the array,this is the answer to my first question.
And to answer my second question what I have searched on the internet that to make the dynamic domain use wildcard * but it will be only used only as the left label of the domain name e.g. *.example.com.,no other positions the * will work.
I hope this will help others who also faced the same problem.

Related

Display google navigation based on given locations

I am working on google maps integration I am trying to display google navigation at present I am using the following code. I am trying to display like google navigation based on location what I pass through the api
NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&alternateroutes=false&sensor=true" ,12.920631,77.670494,8.3075,77.2218]];
NSURLResponse *res;
NSError *err;NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&alternateroutes=false&sensor=true" ,12.920631,77.670494,8.3075,77.2218]];
NSURLResponse *res;
NSError *err;
NSData *data=[NSURLConnection sendSynchronousRequest:[[NSURLRequest alloc] initWithURL:url] returningResponse:&res error:&err];
if(data)
{
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if(dic)
{
NSArray *routes=dic[#"routes"];
NSArray *legs=routes[0][#"legs"];
NSArray *steps=legs[0][#"steps"];
NSLog(#"the legs are:%#",steps);
NSMutableArray *textsteps=[[NSMutableArray alloc] init];
NSMutableArray *latlong=[[NSMutableArray alloc]init];
for(int i=0; i< [steps count]; i++){
NSString *html=steps[i][#"html_instructions"];
[latlong addObject:steps[i][#"end_location"]];
NSLog(#"the data:%#",steps[i][#"end_location"]);
[textsteps addObject:html];
encodedPath = [[[steps objectAtIndex:i] valueForKey:#"polyline"] valueForKey:#"points"];
[self polylineWithEncodedString:encodedPath];
polyline.strokeColor = [UIColor redColor];
polyline.strokeWidth = 2.f;
polyline.map = mapView;
NSLog(#"the encoded patg:%#",encodedPath);
GMSMarker *marker1 = [[GMSMarker alloc]init];
marker1.map = mapView;
NSLog(#"Direction path");
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"" message:#"Connection Error" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:#"", nil];
[alert show];
}
I am expecting an output like
You want to show same direction, time and everything as Google Maps do. Google Maps SDK of iOS will draw a path for you on maps.
You can use the Google Direction API to get and request for direction between source and destination. You can use GMSPolyline to draw it.
But other things, like where to take a turn, whats time is left to reach the destination and other things, you need to manage manually. If you want to show same as Google, you need to make URL and open in WebView.
You can see URLSchema documentation for more detail.
Hoping you are expecting like this code
if ([[UIApplication sharedApplication] canOpenURL:
[NSURL URLWithString:#"comgooglemaps://"]]) {
[[UIApplication sharedApplication] openURL:
[NSURL URLWithString:#"comgooglemaps://?center=40.765819,-73.975866&zoom=14&views=traffic"]];
} else {
NSLog(#"Can't use comgooglemaps://");
}

How to Implement Map Places autocomplete in Baidu Map for IOS SDK

This is my first time that I am using Baidu API. I am having problem implementing Baidu places auto-complete API in my project. I am using the Baidu developers link to http://lbsyun.baidu.com/index.php?title=iossdk.
someone please give me to some tutorial in this regard?
i am following this tutorial. link
but in this tutorial i can not receive json file, give me a error
{ "Status": 102, "message": "MCODE parameter is not present, mobile
type mcode required parameter"}
Seems you should use the POI Search module of BaiduMapKit.Try this.
BMKCitySearchOption *citySearchOption = [[BMKCitySearchOption alloc]init];
citySearchOption.pageIndex = curPage;//here is the page index , you can set it to 0
citySearchOption.pageCapacity = 10;
citySearchOption.city= #"上海";//here is the city where you want to search the road
citySearchOption.keyword = #"淮海路";//here is the road name or someplace name you want to search
BOOL flag = [_poisearch poiSearchInCity:citySearchOption];
if(flag) {
_nextPageButton.enabled = true;
NSLog(#"success");
}
else {
_nextPageButton.enabled = false;
NSLog(#"fail");
}
Implement AutoComplete In Baidu Map using Baidu Web API
- (void)viewDidLoad {
BaseString = #"http://api.map.baidu.com/place/v2/suggestion?query=";
ak = #"56dIEtBAp1CU7u8ZMcq8DyUH2mVsn38x"; mcode = #"com.baidu.Baidu-Map-Demo";
regionkey = #"中国";
PathString = #"http://api.map.baidu.com/direction/v2/transit?origin=";
self .mapView .userTrackingMode = BMKUserTrackingModeFollow;
// 2. Set the map type self.mapView.mapType = BMKMapTypeStandard;
// 3. Set Agent self.mapView.delegate = self;
[super viewDidLoad];
mapView.frame = CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height);
mapView.delegate = self; anotation = [[BMKPointAnnotation alloc]init];
destination = [[BMKPointAnnotation alloc]init];
PathUrl = [[NSURL alloc]init];
finalPathArray = [[NSMutableArray alloc]init];
session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
downloadURL = [[NSURL alloc]init];
path = [[BMKPolyline alloc]init];
flag = 0;
}
-(void)GetSuggestion: (NSString *)query {
NSString *stringUrl = [NSString stringWithFormat:#"%#%#&page_size=10&page_num=0&scope=1&region=%#&output=json&ak=%#&mcode=%#",BaseString,query,regionkey,ak,mcode]; stringUrl = [stringUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
downloadURL = [NSURL URLWithString:stringUrl];
if (downloadURL != nil) {
if (DownloadTask != nil) {
[DownloadTask suspend];
}
DownloadTask = [session dataTaskWithURL:downloadURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *AutocompleteData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
resultArray = AutocompleteData[#"result"];
tbl_result.hidden = NO;
[tbl_result reloadData];
}];
[DownloadTask resume];
}
}
MCODE parameter means your bundle id must spacify bundle id with urlFor example write url for autocomplete FOR Autocomplete use this function

Proper way to use SFSpeechRecognizer?

I'm trying to use SFSpeechRecognizer but I don't have a way to test if I'm implementing it correctly, and since its a relatively new class i couldn't find a sample code (I don't know swift). Am I making any unforgivable mistakes/missing something ?
[SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status){
if (status == SFSpeechRecognizerAuthorizationStatusAuthorized) {
SFSpeechRecognizer* recognizer = [[SFSpeechRecognizer alloc] init];
recognizer.delegate = self;
SFSpeechAudioBufferRecognitionRequest* request = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
request.contextualStrings = #[#"data", #"bank", #"databank"];
SFSpeechRecognitionTask* task = [recognizer recognitionTaskWithRequest:request resultHandler:^(SFSpeechRecognitionResult* result, NSError* error){
SFTranscription* transcript = result.bestTranscription;
NSLog(#"%#", transcript);
}];
}
}];
I´m trying too but this code works for me, after all SFSpeechRecognizer and SFSpeechAudioBufferRecognitionRequest are not the same, so I think (haven´t tested) you have to ask for different permissions (have you asked for permissions before? to use the microphone and the speechRecognition?). Ok here´s the code:
//Available over iOS 10, only for maximum 1 minute, need internet connection; can be sourced from an audio recorded file or over the microphone
NSLocale *local =[[NSLocale alloc] initWithLocaleIdentifier:#"es-MX"];
speechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:local];
NSString *soundFilePath = [myDir stringByAppendingPathComponent:#"/sound.m4a"];
NSURL *url = [[NSURL alloc] initFileURLWithPath:soundFilePath];
if(!speechRecognizer.isAvailable)
NSLog(#"speechRecognizer is not available, maybe it has no internet connection");
SFSpeechURLRecognitionRequest *urlRequest = [[SFSpeechURLRecognitionRequest alloc] initWithURL:url];
urlRequest.shouldReportPartialResults = YES; // YES if animate writting
[speechRecognizer recognitionTaskWithRequest: urlRequest resultHandler: ^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error)
{
NSString *transcriptText = result.bestTranscription.formattedString;
if(!error)
{
NSLog(#"transcriptText");
}
}];

VPN is stopping during network is switching from wifi to mobile data. VPN is connected programmatically in iOS

I am using Network Extension framework for configure and connect VPN server programmatically. I can start and stop VPN. I have written following code to configure VPN in viewDidLoad.
NEVPNManager *manager = [NEVPNManager sharedManager];
[manager loadFromPreferencesWithCompletionHandler:^(NSError *error) {
if(manager.protocol == nil)
{
NSString *filePath = [[NSBundle bundleForClass:[self class]] pathForResource:#"VPNCert" ofType:#"p12"];
NSData *certData = [NSData dataWithContentsOfFile:filePath];
NSString *certPassword = #"password";
NSString *vpnUsername = #"username";
NSString *vpnPassword = #"password";
NSString *vpnUrl = #"VPN Server IP";
// This saves my credentials to the keychain and returns a persistent keychain reference
NSData *passRef = [self addVPNCredentialsToKeychain:vpnUsername withPassword:vpnPassword];
NEVPNProtocolIPSec *p = [[NEVPNProtocolIPSec alloc] init];
p.authenticationMethod = NEVPNIKEAuthenticationMethodCertificate;
p.serverAddress = vpnUrl;
p.username = vpnUsername;
p.passwordReference = passRef;
p.identityData = certData;
p.identityDataPassword = certPassword;
p.disconnectOnSleep = NO;
p.useExtendedAuthentication = YES;
manager.protocol = p;
manager.enabled = YES;
[manager setOnDemandEnabled:NO];
[manager setLocalizedDescription:#"VPN Network"];
[manager saveToPreferencesWithCompletionHandler:^(NSError *error) {
if(error)
{
NSLog(#"Load error: %#", error);
}
}];
}
}];
I also wrote code for start VPN when button is pressed.
- (IBAction)buttonPressed:(id)sender {
NEVPNManager *manager = [NEVPNManager sharedManager];
[manager loadFromPreferencesWithCompletionHandler:^(NSError *error) {
if (!error)
{
NSError *startError = [[NSError alloc] init];
[[NEVPNManager sharedManager].connection startVPNTunnelAndReturnError:&startError];
}
}];
}
Cases working for me.
If i connect VPN in mobile data and switched to wifi this case VPN is not disconnecting.
Also working if i connect VPN in mobile data and switched to wifi and then back to mobile data VPN is not disconnecting.
Problem is
If i connect VPN in wifi and then switch to mobile data, in this case VPN is stopping. I want VPN must stop only when user will stop the VPN.
Is any steps are missing while configuring VPN because of that VPN is stopping?
Thanks in Advance.
You would need to add rules to keep the connection persisted. Also enable onDemand [manager setOnDemandEnabled:YES];
Swift
let connectRule = NEOnDemandRuleConnect()
connectRule.interfaceTypeMatch = .any
let disconnectRule = NEOnDemandRuleDisconnect()
disconnectRule.probeURL = URL(string:VPNCredentialsModel.instance.vpnProbeURL()!)

How to view txt/pdf flle on Google drive in UIWebView

I am working on an App in which I require to access to files stored on Google drive,which works well.
Now, I am trying to display that selected file on the device, I am using UIWebView for that purpose. I have read the documents from Google, I could not find anything in relation with viewing the file(txt/pdf/spread sheet etc).
Here is my code -- I am firing when user taps on a cell of UITableView:
GTLDriveFile *file = [loadedFiles objectAtIndex:indexPath.row];
GTMHTTPFetcher * fetcher = [applicationDelegate.serviceDriveGtl.fetcherService fetcherWithURLString:file.downloadUrl];
[fetcher beginFetchWithCompletionHandler:^(NSData * data,NSError * error) {
if (error != nil) {
NSLog(#"ERROR ON LOADING FILE:%#", [error localizedDescription]);
} else {
NSString * link = [[NSString alloc] initWithData:data
encoding:NSUTF32StringEncoding];
DisplayViewController * displayView = [[DisplayViewController alloc] init];
[displayView showDocumentOnLink:link];
[self.navigationController pushViewController:displayView animated:YES];
}
Now, Here is how I am populating it WebView:
I am collecting the "link" variable in "getLink" in "DisplayViewController".
displayWebView = [[UIWebView alloc] init];
[displayWebView setFrame:CGRectMake(posX, posY+230, width, 200)];
[displayWebView setDelegate:self];
[self.view addSubview:displayWebView];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:getLink]];
[displayWebView loadRequest:request];
What am I missing here ? Why does the WebView not populate the file contents ?
Any help with truly appreciated,
Thanks

Resources