calculateDirectionsWithCompletionHandler: not called, ETA not get - mapkit

Working on Map application, I want to find the Expected time to reach destination point without use any api like maps.google.
any help?
Below is the code :
MKPlacemark* placemark = [[MKPlacemark alloc] initWithCoordinate:new_coordinate addressDictionary:nil];
MKMapItem* destinationMapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
MKDirectionsRequest *request = [MKDirectionsRequest new];
request.source = [MKMapItem mapItemForCurrentLocation];
request.destination = destinationMapItem;
request.transportType = MKDirectionsTransportTypeAutomobile;
MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
[directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
MKRoute *route = response.routes.firstObject;
NSMutableString *Str = [NSMutableString new];
int counter = 1;
for (MKRouteStep *step in route.steps) {
[Str appendFormat:#"%d %#", counter, step.instructions];
counter++;
}
}];
No Error given but not called portion inside calculateDirectionsWithCompletionHandler..

Related

How to draw Polyline based on route in Mkmapview

Hi all I need to display Polyline in MKapview. I have done that but I need to show Polyline based on route. I'm getting like below image if am using location did update then it comes good i am try to store latitude and longitude then next time i have to displayed previous Polyline in that time i am not getting, please help me
- (void)drowRoautLines_FromLocation:(CLLocationCoordinate2D)FromLocation ToLocation:(CLLocationCoordinate2D)ToLocation
{
MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:FromLocation
addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:#"",#"", nil]];
MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];
[srcMapItem setName:#"Source"];
MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:ToLocation
addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:#"",#"", nil]];
MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destination];
[distMapItem setName:#"Destination"];
MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
[request setSource:srcMapItem];
[request setDestination:distMapItem];
[request setTransportType:MKDirectionsTransportTypeAutomobile];
MKDirections *direction = [[MKDirections alloc]initWithRequest:request];
[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error)
{
[self ShowLoading:NO];
NSLog(#"response = %#",response);
NSLog(#"error = %#",error);
NSArray *arrRoutes = [response routes];
if (arrRoutes.count == 0)
{
//Show Error Message.
}
else
{
[arrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
MKRoute *rout = obj;
MKPolyline *line = [rout polyline];
[mapView addOverlay:line];
NSLog(#"Rout Name : %#",rout.name);
NSLog(#"Total Distance (in Meters) :%f",rout.distance);
NSArray *steps = [rout steps];
NSLog(#"Total Steps : %lu",(unsigned long)[steps count]);
[steps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
//NSLog(#"Rout Instruction : %#",[obj instructions]);
}];
}];
}
}];
}

Core Data managed object context save not working

I am trying to write data to persistent storage with managed object context. inserting simple static data. save is returning no errors but fetch is not returning any results. here is my code:
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"MyDB" withExtension:#"momd"];`
NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
NSAssert(mom!=nil, #"Error in initializing Managed Object Model");
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[moc setPersistentStoreCoordinator:psc];
[self setManagedObjectContext:moc];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsURL = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *storeURL = [documentsURL URLByAppendingPathComponent:#"MyDB.sqllite"];
NSError *error = nil;
NSPersistentStoreCoordinator *pscStore = [moc persistentStoreCoordinator];
NSPersistentStore *store = [pscStore addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
NSAssert(store!=nil,#"Error in initializing PSC:%#\n%#",[error localizedDescription],[error userInfo]);
//insert
Schedule *schedule = [NSEntityDescription insertNewObjectForEntityForName:#"Schedule" inManagedObjectContext:moc];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *sessionEndDateReturned = [NSDate alloc];
sessionEndDateReturned = [dateFormatter dateFromString:#"24-04-2016"];
NSDate *sessionStartDateReturned = [NSDate alloc] ;
sessionStartDateReturned = [dateFormatter dateFromString:#"25-04-2016"];
//schedule.category = #"cat";
schedule.about = #"testabout";
schedule.endDate = sessionEndDateReturned;
schedule.eventId = #"e1";
schedule.sessionID = #"s1";
schedule.roomNumber = #"r1";
schedule.startDate = sessionStartDateReturned;
schedule.topic = #"topic1";
schedule.type = #YES;
NSLog(#"inserted objs:%#",moc.insertedObjects);
//save
NSError *insertError = nil;
if(![moc save:&insertError]){
NSLog(#"%# %#",insertError,insertError.localizedDescription);
}
//fetch
NSFetchRequest *fetchReq = [NSFetchRequest fetchRequestWithEntityName:#"Schedule"];
NSError *fetchError = nil;
NSArray *result =[moc executeRequest:fetchReq error:&fetchError];
if(fetchError){
NSLog(#"fetch Error: %#",fetchError.localizedDescription);
}
else
{
NSLog(#"myFetch Result:%#",result);
}
can anybody tell me where i am going wrong?
everything is fine in the above code except fetching part. only small change is required. Save is happening fine, problem only with fetch.
change the fetch execute with below line:
NSArray *result =[moc executeFetchRequest:fetchReq error:&error];
I was doing executeRequest instead of executeFetchRequest :|

Driving route ios7 in India

I need to show a driving route in iOS 7. I know we can use MKDirections for this purpose, but the problem is Apple Maps will not showing driving routes in India. When I Googled I have found if Google Maps is installed on an iPhone device we can use it show directions, otherwise we can't show
directions. Can we use Google Maps in iOS? Do Apple allow to use google map in iOS 7.
Below is the code which i used:
MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.776142, -122.424774)
addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:#"",#"", nil] ];
// MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(10.00145, 76.2828)
addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:#"",#"", nil] ];
MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];
[srcMapItem setName:#""];
MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.73787, -122.373962)
addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:#"",#"", nil] ];
// MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(9.950012, 76.349988)
addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:#"",#"", nil] ];
MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destination];
[distMapItem setName:#""];
MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
[request setSource:srcMapItem];
[request setDestination:distMapItem];
[request setTransportType:MKDirectionsTransportTypeWalking];
MKDirections *direction = [[MKDirections alloc]initWithRequest:request];
[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
NSLog(#"response = %#",response);
NSArray *arrRoutes = [response routes];
[arrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
MKRoute *rout = obj;
MKPolyline *line = [rout polyline];
[self.mkMapView addOverlay:line];
NSLog(#"Rout Name : %#",rout.name);
NSLog(#"Total Distance (in Meters) :%f",rout.distance);
NSArray *steps = [rout steps];
//NSLog(#"Total Steps : %d",[steps count]);
[steps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"Rout Instruction : %#",[obj instructions]);
NSLog(#"Rout Distance : %f",[obj distance]);
}];
}];
}];
You can use google maps easily take a webview and parse the string given below
NSString *urlAddress = #"http://maps.google.co.in/maps?hl=en&tab=wl";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
self.mapView.showsUserLocation = YES;
self.locationController = [[CoreLocationController alloc] init];
self.locationController.delegate = self;
[self.locationController.locationManager startUpdatingLocation];
// Do any additional setup after loading the view.
- (void)update:(CLLocation *)location {
self.lblLatitude.text= [NSString stringWithFormat:#"Latitude %f", [location coordinate].latitude];
self.lblLongitude.text = [NSString stringWithFormat:#"Longitude %f", [location coordinate].longitude];
}
- (void)locationError:(NSError *)error {
self.lblLatitude.text = [error description];
self.lblLongitude.text = nil;
}

Address to coordinate in objective c in google map

I have 60 address and I want to add the pin for every address. I want to use google maps and not Apple maps. I have a loop outside, and calling this method for 100 elements.
And some times I got this error: *** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array
And the error is not regular, I mean the error does not corresponds to an exact address. Sometimes I got 20 errors, sometimes 15,...
Does anyone know how to resolve it?
thank you
- (CLLocationCoordinate2D) getLocationFromAddress:(NSString*) address
{
NSError *error = nil;
NSString *lookUpString;
NSDictionary *jsonDict;
NSData *jsonResponse;
NSArray *locationArray;
lookUpString = [[NSString alloc] initWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true", address];
lookUpString = [lookUpString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
jsonResponse = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:lookUpString]];
jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
locationArray = [[NSArray alloc] init];
locationArray = [[[jsonDict valueForKey:#"results"] valueForKey:#"geometry"] valueForKey:#"location"];
#try {
locationArray = [locationArray objectAtIndex:0];
NSLog(#" LOADING, %d, %d, %d", [locationArray count], [jsonDict count], [jsonResponse length]);
}
#catch (NSException *exception) {
NSLog(#"ERROR LOADING, %d, %d, %d", [locationArray count], [jsonDict count], [jsonResponse length]);
}
#finally {
}
NSString *latitudeString = [[NSString alloc] init];
latitudeString = [locationArray valueForKey:#"lat"];
NSString *longitudeString = [[NSString alloc] init];
longitudeString = [locationArray valueForKey:#"lng"];
NSString *statusString = [[NSString alloc] init];
statusString = [jsonDict valueForKey:#"status"];
double latitude = 0.0;
double longitude = 0.0;
if ([statusString isEqualToString:#"OK"])
{
latitude = [latitudeString doubleValue];
longitude = [longitudeString doubleValue];
}
else
NSLog(#"Something went wrong, couldn't find address");
_location.longitude = longitude;
_location.latitude = latitude;
return _location;
}

objective c Core Data - Attributes aren't saved persistent

i need help!!!^^
I write in my attributes (name,prename) the two names of the person and save them. If i try to access the attrubutes in another view then they are nil. I don't understand why?!?
I did it this way. I get the profileContext with the method getProfile and i access the Attributes with the Dot-Notation, then i save it. My NSLog show me the right name and my fetch too.
ownProfile = [[MyProfile alloc] init];
profileContext = [ownProfile getProfile];
ownProfile = (MyProfile*)[NSEntityDescription insertNewObjectForEntityForName:#"MyProfile" inManagedObjectContext:profileContext];
ownProfile.Vorname = #"Max";
ownProfile.Nachname = #"Wilson";
NSLog(#"%#",ownProfile.Nachname);
if ([profileContext hasChanges]) {
NSLog(#"It has changes!");
[profileContext save:nil];
}
//Fetching
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"MyProfile" inManagedObjectContext:profileContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSArray *array = [profileContext executeFetchRequest:request error:nil];
for (int i=0; i < [array count]; i++) {
MyProfile *object = [array objectAtIndex:i];
NSLog(#"Name: %#",object.Nachname);
}
if i try to access the attributes in another ViewController subclass they are nil. This is the code:
- (void)viewDidLoad {
[super viewDidLoad];
ownProfile = [[MyProfile alloc] init];
NSManagedObjectContext *profileContext = [ownProfile getProfile];
ownProfile = [NSEntityDescription insertNewObjectForEntityForName:#"MyProfile" inManagedObjectContext:profileContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"MyProfile" inManagedObjectContext:profileContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
[request setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSArray *array = [profileContext executeFetchRequest:request error:nil];
[request release];
MyProfile *object = [array objectAtIndex:[array count]-1];
NSLog(#"%#",object);
}
my getProfile method is in the NSManagedObjectClass and look like this:
-(NSManagedObjectContext*) getProfile {
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],
NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES],
NSInferMappingModelAutomaticallyOption, nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSLog(#"basePath = %#",basePath);
NSURL *storeUrl = [NSURL fileURLWithPath:[basePath stringByAppendingFormat:#"CoreData.sqlite"]];
NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[NSManagedObjectModel mergedModelFromBundles:nil]];
NSLog(#"PersistentStore = %#",persistentStoreCoordinator);
NSError *error = nil;
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
NSLog(#"error loading persistent store..");
[[NSFileManager defaultManager] removeItemAtPath:storeUrl.path error:nil];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
NSManagedObjectContext *profile = [[NSManagedObjectContext alloc] init];
[profile setPersistentStoreCoordinator:persistentStoreCoordinator];
return profile;
}
Please help me!!!^^
Hey guys...I solved my problem!!! :)
My fault was that I add in the viewDidLoad-Method in the line
ownProfile = [NSEntityDescription insertNewObjectForEntityForName:#"MyProfile" inManagedObjectContext:profileContext];
another object in the persistentStore and i was always reading the new object where the attributes are nil...of course^^