i display route from start to end point in mapView in iphone and i done it.But after one day i open this project and it does not display route because UICGDirectionsDelegate functions are not called. I dont know why its happen kindly some body guide me about this problem.Many thanks and my sample code is here`
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
if (diretions.isInitialized) {
[self update];
}
routeOverlayView = [[UICRouteOverlayMapView alloc] initWithMapView:mapViews];
diretions = [UICGDirections sharedDirections];
diretions.delegate = self;
}
- (IBAction)backButton:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)update {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
UICGDirectionsOptions *options = [[UICGDirectionsOptions alloc] init];
options.travelMode = travelMode;
if (is_route) {
startPoint = [NSString stringWithFormat:#"%f,%f",APPDELEGATE.user_latitude,APPDELEGATE.user_longitude];
endPoint = [NSString stringWithFormat:#"%#,%#",routeObj.latitude,routeObj.longitude];
destination = poiObj.english_title;
}else {
startPoint = [NSString stringWithFormat:#"%f,%f",APPDELEGATE.user_latitude,APPDELEGATE.user_longitude];
endPoint = [NSString stringWithFormat:#"%# ,%#",poiObj.latitude,poiObj.longitude];
destination = routeObj.starting_poi_name;
}
[diretions loadWithStartPoint:startPoint endPoint:endPoint options:options];
}
- (void)moveToCurrentLocation:(id)sender {
[mapViews setCenterCoordinate:[mapViews.userLocation coordinate] animated:YES];
}
- (void)addPinAnnotation:(id)sender {
UICRouteAnnotation *pinAnnotation = [[UICRouteAnnotation alloc] initWithCoordinate:[mapViews centerCoordinate]
title:nil
annotationType:UICRouteAnnotationTypeWayPoint];
[mapViews addAnnotation:pinAnnotation];
}
#pragma mark <UICGDirectionsDelegate> Methods
- (void)directionsDidFinishInitialize:(UICGDirections *)directions {
[self update];
}
- (void)directions:(UICGDirections *)directions didFailInitializeWithError:(NSError *)error {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Map Directions" message:[error localizedFailureReason] delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
}
- (void)directionsDidUpdateDirections:(UICGDirections *)directions {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
// Overlay polylines
UICGPolyline *polyline = [directions polyline];
NSArray *routePoints = [polyline routePoints];
[routeOverlayView setRoutes:routePoints];
// Add annotations
currentLocation = #"You are here";
UICRouteAnnotation *startAnnotation = [[UICRouteAnnotation alloc] initWithCoordinate:[[routePoints objectAtIndex:0] coordinate]
title:currentLocation
annotationType:UICRouteAnnotationTypeStart];
UICRouteAnnotation *endAnnotation = [[UICRouteAnnotation alloc] initWithCoordinate:[[routePoints lastObject] coordinate]
title:destination
annotationType:UICRouteAnnotationTypeEnd];
[mapViews addAnnotations:[NSArray arrayWithObjects:startAnnotation, endAnnotation, nil]];
}
- (void)directions:(UICGDirections *)directions didFailWithMessage:(NSString *)message {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Map Directions" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
}
`
In UICGRoute.m
Replace this
NSArray *stepDics;
NSDictionary *k;
for (int i = 0; i<allKeys.count; i++) {
k = [dictionaryRepresentation objectForKey:[allKeys objectAtIndex:i]];
if ([k objectForKey:#"Steps"]) {
stepDics = [k objectForKey:#"Steps"];
break;
}
}
with
NSDictionary *k = [dictionaryRepresentation objectForKey:[allKeys objectAtIndex:[allKeys count] - 1]];
NSArray *stepDics = [k objectForKey:#"Steps"];
Related
The problem I'm having it that when I long touch the map it saves the data to Core Data and I can retrieve this data by NSLogs but I cannot figure out how to create multiple map markers from this data. Can anyone give me an example of a for loop for drawing these markers?
-(void) mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate{
location = coordinate;
[self alertview1];
}
- (void) alertview1 {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Save Map Location" message:#"Enter Title & Description" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
[av setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
[[av textFieldAtIndex:1] setSecureTextEntry:NO];
[[av textFieldAtIndex:0] setPlaceholder:#"Title"];
[[av textFieldAtIndex:1] setPlaceholder:#"Description"];
[av show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex != alertView.cancelButtonIndex) {
markerTitle = [alertView textFieldAtIndex:0].text;
markerSnippet = [alertView textFieldAtIndex:1].text;
NSLog(#"1 %#", [alertView textFieldAtIndex:0].text);
NSLog(#"2 %#", [alertView textFieldAtIndex:1].text);
[self saveMarker];
}
- (void) saveMarker{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:#"Marker" inManagedObjectContext:context];
[newDevice setValue:[NSNumber numberWithDouble:location.latitude] forKey:#"latitude"];
[newDevice setValue:[NSNumber numberWithDouble:location.longitude] forKey:#"longitude"];
[newDevice setValue:markerTitle forKey:#"title"];
[newDevice setValue:markerSnippet forKey:#"snippet"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
[self dismissViewControllerAnimated:YES completion:nil];
[self fetchMarkers];
}
- (void) fetchMarkers {
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Marker"];
self.markers = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSArray *title = [self.markers valueForKey:#"Title"];
NSArray *snippet = [self.markers valueForKey:#"Snippet"];
NSArray *latitude = [self.markers valueForKey:#"Latitude"];
NSArray *longitude = [self.markers valueForKey:#"Longitude"];
NSLog (#"%#", title);
NSLog (#"%#", snippet);
NSLog (#"%#", latitude);
NSLog (#"%#", longitude);
double lat = [latitude doubleValue];
double lng = [longitude doubleValue];
for (GMSMarker *marker in title) {
GMSMarker *mkr = [[GMSMarker alloc] init];
[mkr setPosition:CLLocationCoordinate2DMake(lat,lng)];
[mkr setAnimated:YES];
[mkr setTitle:title];
[mkr setSnippet:snippet];
[mkr setMap:self.mapView1];
}
}
After banging my head against the wall for hours and taking a few shots it finally came to me and was very simple. I stuck the data from core data in separate arrays and indexes the markers then indexed the arrays in a variable. Anyway here is the code. If anyone else has a better way of doing this please let me know. I am still learning Objective C and only started a couple months ago so there probably is a better solution but this at least works.
-(void) mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate{
location = coordinate;
[self alertview1];
}
- (void) alertview1 {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Save Map Location" message:#"Enter Title & Description" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
[av setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
// Alert style customization
[[av textFieldAtIndex:1] setSecureTextEntry:NO];
[[av textFieldAtIndex:0] setPlaceholder:#"Title"];
[[av textFieldAtIndex:1] setPlaceholder:#"Description"];
[av show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex != alertView.cancelButtonIndex) {
markerTitle = [alertView textFieldAtIndex:0].text;
markerSnippet = [alertView textFieldAtIndex:1].text;
NSLog(#"1 %#", [alertView textFieldAtIndex:0].text);
NSLog(#"2 %#", [alertView textFieldAtIndex:1].text);
[self saveMarker];
} else {
// this is where you would handle any actions for "Cancel"
}
}
- (void) saveMarker{
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new managed object
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:#"Marker" inManagedObjectContext:context];
[newDevice setValue:[NSNumber numberWithDouble:location.latitude] forKey:#"latitude"];
[newDevice setValue:[NSNumber numberWithDouble:location.longitude] forKey:#"longitude"];
[newDevice setValue:markerTitle forKey:#"title"];
[newDevice setValue:markerSnippet forKey:#"snippet"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
[self dismissViewControllerAnimated:YES completion:nil];
[self fetchMarkers];
}
- (void) fetchMarkers {
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Marker"];
self.markers = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSMutableArray *title = [self.markers valueForKey:#"Title"];
NSMutableArray *snippet = [self.markers valueForKey:#"Snippet"];
NSMutableArray *latitude = [self.markers valueForKey:#"Latitude"];
NSMutableArray *longitude = [self.markers valueForKey:#"Longitude"];
for (int i = 0; i < [title count]; i++){
GMSMarker *mkr = [[GMSMarker alloc] init];
double lat = [[latitude objectAtIndex:i] doubleValue];
double lng = [[longitude objectAtIndex:i] doubleValue];
NSString *T = [title objectAtIndex:i];
NSString *S = [snippet objectAtIndex:i];
[mkr setPosition:CLLocationCoordinate2DMake(lat, lng)];
[mkr setAnimated:YES];
[mkr setTitle:T];
[mkr setSnippet:S];
[mkr setMap:self.mapView1];
}
Right now I am setting my region based on users current location. I would like to now set the zoom level so I can see the users current location and the nearest pin that is being pulled in via json.
Not until run time will the app know the number of pins or the locations of said pins.
Here is what I have so far.
#implementation LocationsViewController
#synthesize mapView;
#synthesize locationManager;
#synthesize phone;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
self.title = NSLocalizedString(#"Locations", #"Locations");
self.tabBarItem.image = [UIImage imageNamed:#"locations"];
}
return self;
}
- (void)dealloc
{
[super dealloc];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
//Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"New latitude: %f", newLocation.coordinate.latitude);
NSLog(#"New longitude: %f", newLocation.coordinate.longitude);
MKCoordinateRegion region;
region.center.latitude =newLocation.coordinate.latitude;
region.center.longitude= newLocation.coordinate.longitude;
region.span.longitudeDelta=0.2;
region.span.latitudeDelta =0.2;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
//[locationManager stopUpdatingLocation];
}
-(void)viewDidDisappear:(BOOL)animated
{
[locationManager stopUpdatingLocation];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[locationManager startUpdatingLocation];
if([self connectedToNetwork] != YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"OH NO!" message:#"To get the latest information you need a data or wi-fi connection" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
else
{
[mapView removeAnnotations:mapView.annotations];
NSString *urlString = [NSString stringWithFormat:#"http://www.mywebsite.com/json.json"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
for(id key in json) {
id value = [json objectForKey:key];
NSString *titlePin = [value valueForKey:#"address"];
NSString *address = [value valueForKey:#"title"];
NSString *latitude = [value valueForKey:#"latitude"];
NSString *longitude = [value valueForKey:#"longitude"];
NSArray* foo = [address componentsSeparatedByString: #":"];
NSString* address2 = [foo objectAtIndex: 0];
phone = [foo objectAtIndex: 1];
double myLatitude = [latitude doubleValue];
double myLongitude = [longitude doubleValue];
MKCoordinateRegion location1;
location1.center.latitude =myLatitude;
location1.center.longitude= myLongitude;
location1.span.longitudeDelta=0.1;
location1.span.latitudeDelta =0.1;
MapAnnotation *ann1 =[[[MapAnnotation alloc] init] autorelease];
ann1.title=[NSString stringWithFormat:#"%#",titlePin];
ann1.subtitle=[NSString stringWithFormat:#"%#",address2];
ann1.phone=[NSString stringWithFormat:#"%#",phone];
ann1.coordinate= location1.center;
[mapView addAnnotation:ann1];
[phone retain];
}
}
}
-(MKAnnotationView *) mapView:(MKMapView *)mapView2 viewForAnnotation:(id<MKAnnotation>)annotation {
if (annotation == mapView2.userLocation) {
return nil;
}else{
MKPinAnnotationView *MyPin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"current"];
MyPin.pinColor = MKPinAnnotationColorPurple;
UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
[advertButton setImage:[UIImage imageNamed:#"mapphone"] forState:UIControlStateNormal];
[advertButton addTarget:self action:#selector(button:) forControlEvents:UIControlEventTouchUpInside];
MyPin.rightCalloutAccessoryView = advertButton;
MyPin.draggable = NO;
MyPin.highlighted = YES;
MyPin.animatesDrop=TRUE;
MyPin.canShowCallout = YES;
return MyPin;
}
}
-(void)button:(id)sender {
UIButton *button = (UIButton *)sender;
MKPinAnnotationView *annotationView = (MKPinAnnotationView*)button.superview.superview;
MapAnnotation *mapAnnotation = annotationView.annotation;
UIDevice *device = [UIDevice currentDevice];
if ([[device model] isEqualToString:#"iPhone"] ) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"tel:%#",mapAnnotation.phone]]];
} else {
UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:mapAnnotation.phone message:#"Your device doesn't support this feature." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[Notpermitted show];
[Notpermitted release];
}
}
- (BOOL) connectedToNetwork
{
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
BOOL internet;
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
internet = NO;
} else {
internet = YES;
}
return internet;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#end
I did something similar, but based on two annotations, not the user's location. You should be able to replace mapView.centerCoordinate with mapView.userLocation.coordinate.
in viewForAnnotation:
CLLocation *centerLoc = [[CLLocation alloc] initWithLatitude:mapView.centerCoordinate.latitude longitude:mapView.centerCoordinate.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:[annotation coordinate].latitude longitude:[annotation coordinate].longitude];
CLLocationDistance distance = [loc2 distanceFromLocation:centerLoc];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(mapView.centerCoordinate, distance*2, distance*2);
MKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion];
[mapView setRegion:adjustedRegion animated:YES];
Note, this code will re-calc the zoom level each time you add an annotation. You may need to save the distance and only change the map if the new distance is greater than the prior distance.
My Map application is on iTune market which runs good on iOS 4 and iOS 5. I have developed this application using Xcode 3.2, iPhone sdk 4.2 on Mac mini having Mac OS 10.6.8.
This application .ipa file is crashing after launching on iOS 6. I am developing app on MacMini and I could not able to run xcode 4.5 to rectify the crash. I am pasting some code which runs on launching. If there is some deprecated methods which causes crash then please help because I am not able to check this code without Mac OS 10.7(Lion)..
- (void)viewDidLoad {
if([appDelegate.markers count] == 0 && [mapView.annotations count] == 0 && UserId.data == 0)
{
[self performSelector:#selector(launchActivity) withObject:nil afterDelay:1.0];
}
}
- (void) launchActivity {
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:#"No Internet Connectivity!" message:#"This app require an internet connection via WiFi or cellular network to work." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}
else
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
if([self.mapView.annotations count] == 1)
{
}
if (locationManager.location == nil)
{
}
else
{
// Change map region using span (degrees)...
MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
MKCoordinateRegion region = MKCoordinateRegionMake
(locationManager.location.coordinate, span);
[mapView setRegion:region animated:YES];
}
mapView.showsUserLocation = YES;
BOOL locationAllowed = [CLLocationManager locationServicesEnabled];
if (locationAllowed==NO)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Location Service Disabled"
message:#"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
else
{
[NSThread detachNewThreadSelector:#selector(updateFilterProgress) toTarget:self withObject:nil]; //NSthread not taken because Default.png stay while loading the results
//========================================================================================== ==================================
//Searching Showroom Locations withing the radius
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
appDelegate = (HettichLocatorAppDelegate *)[[UIApplication sharedApplication] delegate];
CLLocationCoordinate2D location;
NSString *url = [[NSString alloc] initWithFormat:#"http://www.company.com.au/directory/phpsqlsearch_genxml.php?lat=%f&lng=%f&radius=5",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude];
radiusinurl.text = #"5km";
NSURL *URL = [NSURL URLWithString:url];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
//Initialize the delegate.
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
[parser release];
[xmlParser release];
//[URL release];
[url release];
if(success)
{
annobjs = [[NSMutableArray array] retain];
if([appDelegate.markers count] == 0)
{
//some logic
}
else
{
for (int i = 0; i < [appDelegate.markers count]; i++)
{
marker *aMarker = [appDelegate.markers objectAtIndex:i];
location.latitude = [aMarker.lat floatValue];
location.longitude =[aMarker.lng floatValue];
AddressAnnotation *annobj = [[AddressAnnotation alloc] initWithCoordinate:location];
annobj.title = aMarker.name;
annobj.subtitle = aMarker.address;
[annobjs addObject:annobj];
[mapView addAnnotation:annobj];
CLLocationCoordinate2D ausLoc = {location.latitude,location.longitude}; //for zoom in the showroom results region
MKCoordinateSpan ausSpan = MKCoordinateSpanMake(0.108889, 0.169922);
MKCoordinateRegion ausRegion = MKCoordinateRegionMake(ausLoc, ausSpan);
mapView.region = ausRegion;
[annobj release];
[_tableView reloadData];
}
}
}
else
{
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:#"" message:#"Unable to find the results." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}
[pool release];
}
}
}
}
I cannot seem to figure out what to do to resolve this error that I am receiving. I click on a cell which pops a new UITableViewController onto the stack. Once I hit the back button on the Navigation UI when in this controller I receive this error in the debugger but there doesn't seem to be any issue with the app as it doesn't crash or hang and still works fine.
An instance 0x79a8400 of class UITableView was deallocated while key value observers were still registered with it. Observation info was leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger. Here's the current observation info:
(
Context: 0x0, Property: 0x738c010>
)
Code is below and I am using similar code on other UITableViewControllers but not receiving the error.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
pull = [[PullToRefreshView alloc] initWithScrollView:(UIScrollView *) self.tableView];
[pull setDelegate:self];
[self.tableView addSubview:pull];
[tableView.dataSource self];
[tableView.delegate self];
NSString *isAuthenticated = [[NSString alloc] init];
isAuthenticated = [self retrieveUserToken:[[NSUserDefaults standardUserDefaults] valueForKey:#"email"]];
NSNumber *categorySelected = [[NSNumber alloc] init];
categorySelected = [[NSUserDefaults standardUserDefaults] valueForKey:#"category_id"];
if (![isAuthenticated length])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Message" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}else if (categorySelected ==nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"message" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}
[self getTableViewData];
}
- (void)viewDidUnload
{
[self setTableView:nil];
pull = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSString *)retrieveUserToken:(NSString *)user
{
NSError *error = nil;
NSString *username = user;
return [SFHFKeychainUtils getPasswordForUsername:username andServiceName:#"app" error:&error];
}
- (void)getTableViewData
{
URLSingleton *urls = [[URLSingleton alloc] init];
responseData = [NSMutableData data];
NSNumber *categoryID = [[NSNumber alloc] init];
categoryID = [[NSUserDefaults standardUserDefaults] valueForKey:#"category_id"];
NSString *urlComplete = [[NSString alloc] init];
urlComplete = [urls getEvent:categoryID];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlComplete]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[connection start];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return categories.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"cell"];
cell.textLabel.textColor = [UIColor blackColor];
cell.textLabel.text = [categories objectAtIndex:indexPath.row];
return cell;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.tableView reloadData];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Message." delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[pull finishedLoading];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *dictionary = [responseString JSONValue];
NSArray *response = [dictionary valueForKey:#"name"];
NSArray *responseID = [dictionary valueForKey:#"id"];
categories = [[NSMutableArray alloc] initWithArray:response];
eventID = [[NSMutableArray alloc] initWithArray:responseID];
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[pull finishedLoading];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [self.tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
int i = 0;
for(NSString *name in categories)
{
if ([name isEqualToString:cellText])
{
[[NSUserDefaults standardUserDefaults] setValue:[eventID objectAtIndex:i] forKey:#"event_id"];
[[NSUserDefaults standardUserDefaults] setValue:cellText forKey:#"event_name"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
i++;
}
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
if(checkedIndexPath) {
UITableViewCell* uncheckCell = [self.tableView
cellForRowAtIndexPath:checkedIndexPath];
uncheckCell.accessoryType = UITableViewCellAccessoryNone;
}
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
checkedIndexPath = indexPath;
}
-(void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
URLSingleton *urls = [URLSingleton sharedInstance];
NSNumber *event = [[NSNumber alloc] init];
if(editingStyle == UITableViewCellEditingStyleDelete)
{
UITableViewCell *selectedCell = [self.tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
int i = 0;
for(NSString *name in categories)
{
if ([name isEqualToString:cellText])
{
event = [eventID objectAtIndex:i];
[eventID removeObjectAtIndex:i];
}
i++;
}
NSString *reqURL = [[NSString alloc] initWithString:[urls deleteEvent:[event stringValue]]];
NSURLRequest *delReq = [NSURLRequest requestWithURL:[NSURL URLWithString:reqURL]];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:delReq returningResponse: &resp error: &err];
NSString *reply = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
SBJsonParser *parser = [SBJsonParser new];
id content = [reply JSONValue];
if(!content){
NSLog(#"%#", parser.errorTrace);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
return;
}
NSNumber *status = [content valueForKey:#"success"];
NSNumber *one = [[NSNumber alloc] initWithInt:1];
if ([status isEqualToNumber:one])
{
[categories removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Message" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
}
}
}
- (void)pullToRefreshViewShouldRefresh:(PullToRefreshView *)view;
{
NSString *isAuthenticated = [[NSString alloc] init];
isAuthenticated = [self retrieveUserToken:[[NSUserDefaults standardUserDefaults] valueForKey:#"email"]];
NSNumber *categorySelected = [[NSNumber alloc] init];
categorySelected = [[NSUserDefaults standardUserDefaults] valueForKey:#"category_id"];
if (![isAuthenticated length])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Message" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}else if (categorySelected ==nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Message" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}
[self getTableViewData];
}
- (IBAction)createEvent:(id)sender
{
NSString *isAuthenticated = [[NSString alloc] init];
isAuthenticated = [self retrieveUserToken:[[NSUserDefaults standardUserDefaults] valueForKey:#"email"]];
NSNumber *categorySelected = [[NSNumber alloc] init];
categorySelected = [[NSUserDefaults standardUserDefaults] valueForKey:#"category_id"];
if (![isAuthenticated length])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Message" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}else if (categorySelected == nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Alert" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}
AddEventViewController *aevc = [self.storyboard instantiateViewControllerWithIdentifier:#"AddEventViewController"];
[self.navigationController popToViewController:aevc animated:YES];
}
I fixed it by adding the following method
- (void)dealloc
{
[self.tableView removeObserver:pull forKeyPath:#"contentOffset"];
}
How access iPod Library in my iPhone app, like to the user listem music when is playing... like in the gameloft games, or the slide show from the Photos.app ?
Look at MPMusicPlayerController. I read it can access the iPod library. I never used it, and I don't know if it can help you...
- (void)addMusicBtnAction{
MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeAnyAudio];
mediaPicker.delegate = self;
//mediaPicker.prompt = #"Select Audio";
mediaPicker.prompt = NSLocalizedString (#"Select any song from the list", #"Prompt to user to choose some songs to play");
for (UIWindow* window in [UIApplication sharedApplication].windows) {
NSArray* subviews = window.subviews;
if ([subviews count] > 0)
for (UIAlertView *alrt in subviews) {
if ([alrt isKindOfClass:[UIAlertView class]]){
if (alrt.tag == 10020) {
[alrt dismissWithClickedButtonIndex:0 animated:YES];
}
}
}
}
[self presentModalViewController:mediaPicker animated:YES];
//[mediaPicker release];
}
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection
{
NSArray * SelectedSong = [mediaItemCollection items];
if([SelectedSong count]>0){
MPMediaItem * SongItem = [SelectedSong objectAtIndex:0];
NSURL *SongURL = [SongItem valueForProperty: MPMediaItemPropertyAssetURL];
NSString *str = [NSString stringWithFormat:#"%#",SongURL];
appDelegate.musicFilePath = str;
//NSLog(#"Audio Loaded");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Your audio has been selected" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil, nil];
alert.tag = 78787878;
[alert show];
// [alert release];
}
[self dismissModalViewControllerAnimated: YES];
}
// Responds to the user tapping done having chosen no music.
- (void) mediaPickerDidCancel: (MPMediaPickerController *) mediaPicker {
[self dismissModalViewControllerAnimated: YES];
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleBlackOpaque animated:YES];
}