Display google navigation based on given locations - ios

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://");
}

Related

Vpn on demand in ios 9.2

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.

Sharing video with airdrop

I am having some trouble in sharing videos with airdrop. So, i am using the AssetLibrary like this :
else if (conformsToVideo) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Asset Loaded" message:#"Video One Loaded"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
self.mediaAsset = [AVAsset assetWithURL:[info objectForKey:UIImagePickerControllerMediaURL]];
UIActivityViewController * controller = [[UIActivityViewController alloc] initWithActivityItems:#[self.mediaAsset] applicationActivities:nil];
[self presentViewController:controller animated:YES completion:nil];
}
Maybe this is just not the way to do it, I don't know and I didn't find any tutorial about it so if you have one, I will gladly take it.
Now my problem is that when i select a video everything works fine until the UIActivityViewController pops out , i don't have any error but I can't use airdrop (nor any other service BTW) the only thing I can do is press the Cancel button of the UIAVController.
I am using iOS 8.3.
Thanks for your help
Ok, eventually I found an answer, maybe not the best but I put it there in case it helps someone cause I didn't find much on sharing video with airdrop :
NSURL * path = [info objectForKey:UIImagePickerControllerReferenceURL];
BOOL conformsToVideo = (UTTypeConformsTo((__bridge_retained CFStringRef) mediaType, kUTTypeAudiovisualContent));
if (conformsToVideo) {
[self.library assetForURL:path
resultBlock:^(ALAsset *asset) {
ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];
NSString* outputDirectory = [NSString stringWithFormat:#"%#", NSTemporaryDirectory()];
NSString* pathToCopy = [outputDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", assetRepresentation.filename]];
NSUInteger size = (NSUInteger)assetRepresentation.size;
NSMutableData* data = [NSMutableData dataWithLength:size];
NSUInteger bytesRead = [assetRepresentation getBytes:data.mutableBytes fromOffset:0 length:size error:nil];
NSURL * url = nil;
if ([data writeToFile:pathToCopy atomically:YES])
{
NSLog(#"Ok");
url = [NSURL fileURLWithPath:pathToCopy];
UIActivityViewController * controller = [[UIActivityViewController alloc] initWithActivityItems:#[url] applicationActivities:nil];
[self presentViewController:controller animated:YES completion:nil];
}
} failureBlock:^(NSError *error) {
NSLog(#"Failure to use the ALAsset");
}
];
}
I found the solution using this question : Share a video from asset library with AirDrop fails
I am merely adding the previous steps to the code given there, hope it can be useful.

Open Facebook iOS native app WITH back button to my app

I am trying to open facebook app via AppLinks url , it opens user profile/page but does not show button "back to referer app" , I am providing "referer_app_link" data ,
I have generated JSON by this reference http://applinks.org/documentation/#applinknavigationprotocol
NSDictionary *dict = #{
#"target_url" : #"fb://profile/USER_ID",
#"referer_app_link" : #{
#"target_url" : #"MY WEBSITE",
#"url" : #"CALLBACK URL",
#"app_name" : #"MY APP NAME",
#"app_store_id" : #"MY APP STORE ID"
}
};
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *stringUrl = [NSString stringWithFormat:#"fb://applinks?al_applink_data=%#",jsonString];
NSLog(#"String url is %#",stringUrl);
NSURL *url = [NSURL URLWithString:stringUrl];
if([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
} else {
NSLog(#"Cant open %#",url);
}
any ideas ? is Facebook supposed to have "back button" at all ?
my url scheme is set up correctly ...
Update:
NSDictionary contains all valid values , I dont want to publish them at the moment , but url , name , store id ... etc all are valid
Update #2:
Since iOS 9 , this is done by iOS System automatically.
applink is not wired into the FB friend profile page if you simply use the FB Custom URL to link into FB.APP or to safari it will not go back to your app automatically.
The alternative to this is to use the FB IOS SDK and Pick and display the remote user within your app as follows: (code from HelloFacebook sample app (comes with the SDK)
- (IBAction)pickFriendsClick:(UIButton *)sender {
FBFriendPickerViewController *friendPickerController = [[FBFriendPickerViewController alloc] init];
friendPickerController.title = #"Pick Friends";
[friendPickerController loadData];
// Use the modal wrapper method to display the picker.
[friendPickerController presentModallyFromViewController:self animated:YES handler:
^(FBViewController *innerSender, BOOL donePressed) {
if (!donePressed) {
return;
}
NSString *message;
if (friendPickerController.selection.count == 0) {
message = #"<No Friends Selected>";
} else {
NSMutableString *text = [[NSMutableString alloc] init];
// we pick up the users from the selection, and create a string that we use to update the text view
// at the bottom of the display; note that self.selection is a property inherited from our base class
for (id<FBGraphUser> user in friendPickerController.selection) {
if ([text length]) {
[text appendString:#", "];
}
[text appendString:user.name];
}
message = text;
}
[[[UIAlertView alloc] initWithTitle:#"You Picked:"
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil]
show];
}];
}
Note - the sample currently just picked the name property from the FBGraphUser Class instance ....
user will have other properties birthday, sex etc, just lookup header file within the SDK or look up FB documentation.

For-Loop to quick to present View Controller

i want to add multiple passbook passes by running through a array with URLs. The problem is that the loop counts faster than the view controller can present.
Here s my code:
NSArray *passURLArray = [NSArray new];
passURLArray = response;
for (int i = 0; passURLArray.count; i++) {
NSString *passURLString = [NSString stringWithFormat:#"http://test.de%#", [passURLArray objectAtIndex:i]];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:passURLString]];
NSError *error;
PKPass *pass = [[PKPass alloc] initWithData:data error:&error];
[[UIApplication sharedApplication] openURL:[pass passURL]];
PKAddPassesViewController *passVC = [[PKAddPassesViewController alloc] initWithPass:pass];
passVC.delegate = self;
[passVC setDelegate:(id)self];
[self presentViewController:passVC animated:YES completion:nil];
}
I get this error message:
Attempt to present PKAddPassesViewController: 0xca5f7d0 on
PaymentViewController: 0x14882290 which is waiting for a delayed
presention of PKAddPassesViewController: 0xb169470 to complete
Thanks in advance.
Check if you're on the last iteration of the loop. If you are, animate the display, if not, don't animate it.
That said, it's nasty from a user standpoint. You should probably think about a nicer way of presenting, like showing a list or animating between each display when addPassesViewControllerDidFinish: is called.

Publish an image with text on facebook

I would like to post a feed on facebook by using fallback share. It should contain an image and a message. I have tried soo much by changing the params
NSMutableDictionary *postParams =
[[NSMutableDictionary alloc] initWithObjectsAndKeys:
#"http://www.abc.com",#"link",
self.produtObj.productImageURL, #"picture",
self.produtObj.productName, #"name",
self.produtObj.productDescription, #"message",
nil];
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:postParams
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
NSString *alertText;
if (error) {
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
} else {
alertText = [NSString stringWithFormat:
#"Posted action, id: %#",
[result objectForKey:#"id"]];
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil]
show];
}];
With this code, the feed is displayed in a box and clicking on it is taking me to the link spcified. I just want to have an image thumbnail with the story for it not inside the box. Please help me. This is my first question in SOF. So please forgive me for my mistakes.
Thanks in advance. :)
I really prefer to use the UIActivityItemViewConroller for pushing stuff up to facebook.
The user needs to be logged into facebook on their device. You can do that through settings in the Facebook section.
I make the new controller like this for my stuff:
NSMutableArray *stuff = [[NSMutableArray alloc]init];
NSString *textstring = #"Now is the time for all good men to come to the aid of their country. Lorum Ipsum etc";
UIImage *pic = [UIImage imageNamed:#"Icon-Small-50"];//A local image
NSString *URL = #"http://nwc.co/images/nwc-icon-200.gif";//A link to an image
[stuff addObject:textstring];
[stuff addObject:pic];
[stuff addObject:URL];
UIActivityViewController *vc = [[UIActivityViewController alloc]initWithActivityItems:stuff applicationActivities:nil];
[self.navigationController presentViewController:vc animated:YES completion:^{
//do something here when they are done
}];
If you run the above, you'll notice that the text, the local image, and a link to the online image all appear on the post.
And you can exclude other activities, if you don't want to confuse people when the activity icons pop up:
vc.excludedActivityTypes = #[UIActivityTypePrint, UIActivityTypePostToTwitter, UIActivityTypePostToWeibo, UIActivityTypeMail, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll];

Resources