I've tried reading the google places API. and tried to duplicate their work. But I think I'm missing some steps here.
Here is the code for header my header file.
#class SPGooglePlacesAutocompleteQuery;
#interface GoogleMapViewViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate, UISearchBarDelegate, MKMapViewDelegate, UISearchControllerDelegate>
{
NSArray *searchResultPlaces;
SPGooglePlacesAutocompleteQuery *searchQuery;
MKPointAnnotation *selectedPlaceAnnotation;
BOOL shouldBeginEditing;
}
#property (strong, nonatomic) UISearchController *searchController;
#property (retain, nonatomic) IBOutlet MKMapView *mapView;
#end
My implementation file
#import "GoogleMapViewViewController.h"
#import "SPGooglePlacesAutocompleteQuery.h"
#import "SPGooglePlacesAutocompletePlace.h"
#interface GoogleMapViewViewController ()
#property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
#end
#implementation GoogleMapViewViewController
#synthesize mapView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
searchQuery = [[SPGooglePlacesAutocompleteQuery alloc] init];
searchQuery.radius = 100.0;
shouldBeginEditing = YES;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.searchBar.placeholder = #"Search or Address";
self.searchBar.delegate = self;
}
- (void)viewDidUnload {
[self setMapView:nil];
[super viewDidUnload];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [searchResultPlaces count];
}
- (SPGooglePlacesAutocompletePlace *)placeAtIndexPath:(NSIndexPath *)indexPath {
return [searchResultPlaces objectAtIndex:indexPath.row];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"SPGooglePlacesAutocompleteCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.font = [UIFont fontWithName:#"GillSans" size:16.0];
cell.textLabel.text = [self placeAtIndexPath:indexPath].name;
return cell;
}
#pragma mark UITableViewDelegate
- (void)recenterMapToPlacemark:(CLPlacemark *)placemark {
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.02;
span.longitudeDelta = 0.02;
region.span = span;
region.center = placemark.location.coordinate;
[self.mapView setRegion:region];
}
- (void)addPlacemarkAnnotationToMap:(CLPlacemark *)placemark addressString:(NSString *)address {
[self.mapView removeAnnotation:selectedPlaceAnnotation];
selectedPlaceAnnotation = [[MKPointAnnotation alloc] init];
selectedPlaceAnnotation.coordinate = placemark.location.coordinate;
selectedPlaceAnnotation.title = address;
[self.mapView addAnnotation:selectedPlaceAnnotation];
}
- (void)dismissSearchControllerWhileStayingActive {
// Animate out the table view.
NSTimeInterval animationDuration = 0.3;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:animationDuration];
self.searchDisplayController.searchResultsTableView.alpha = 0.0;
[UIView commitAnimations];
[self.searchDisplayController.searchBar setShowsCancelButton:NO animated:YES];
[self.searchDisplayController.searchBar resignFirstResponder];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
SPGooglePlacesAutocompletePlace *place = [self placeAtIndexPath:indexPath];
[place resolveToPlacemark:^(CLPlacemark *placemark, NSString *addressString, NSError *error) {
if (error) {
SPPresentAlertViewWithErrorAndTitle(error, #"Could not map selected Place");
} else if (placemark) {
[self addPlacemarkAnnotationToMap:placemark addressString:addressString];
[self recenterMapToPlacemark:placemark];
[self dismissSearchControllerWhileStayingActive];
[self.searchDisplayController.searchResultsTableView deselectRowAtIndexPath:indexPath animated:NO];
}
}];
}
#pragma mark UISearchDisplayDelegate
- (void)handleSearchForSearchString:(NSString *)searchString {
searchQuery.location = self.mapView.userLocation.coordinate;
searchQuery.input = searchString;
[searchQuery fetchPlaces:^(NSArray *places, NSError *error) {
if (error) {
SPPresentAlertViewWithErrorAndTitle(error, #"Could not fetch Places");
} else {
searchResultPlaces = places;
[self.searchDisplayController.searchResultsTableView reloadData];
}
}];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self handleSearchForSearchString:searchString];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (BOOL)searchController:(UISearchController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self handleSearchForSearchString:searchString];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
#pragma mark UISearchBar Delegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if (![searchBar isFirstResponder]) {
// User tapped the 'clear' button.
shouldBeginEditing = NO;
[self.searchDisplayController setActive:NO];
[self.mapView removeAnnotation:selectedPlaceAnnotation];
}
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
if (shouldBeginEditing) {
// Animate in the table view.
NSTimeInterval animationDuration = 0.3;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:animationDuration];
self.searchDisplayController.searchResultsTableView.alpha = 1.0;
[UIView commitAnimations];
[self.searchDisplayController.searchBar setShowsCancelButton:YES animated:YES];
}
BOOL boolToReturn = shouldBeginEditing;
shouldBeginEditing = YES;
return boolToReturn;
}
#pragma mark MKMapView Delegate
- (MKAnnotationView *)mapView:(MKMapView *)mapViewIn viewForAnnotation:(id <MKAnnotation>)annotation {
if (mapViewIn != self.mapView || [annotation isKindOfClass:[MKUserLocation class]]) {
return nil;
}
static NSString *annotationIdentifier = #"SPGooglePlacesAutocompleteAnnotation";
MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];
if (!annotationView) {
annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationIdentifier];
}
annotationView.animatesDrop = YES;
annotationView.canShowCallout = YES;
UIButton *detailButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[detailButton addTarget:self action:#selector(annotationDetailButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
annotationView.rightCalloutAccessoryView = detailButton;
return annotationView;
}
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
// Whenever we've dropped a pin on the map, immediately select it to present its callout bubble.
[self.mapView selectAnnotation:selectedPlaceAnnotation animated:YES];
}
- (void)annotationDetailButtonPressed:(id)sender {
// Detail view controller application logic here.
}
#end
I am really confused now to my implementation file as I cannot really understand what is in there TBH.plus some codes here are mostly deprecated. Someone care to give a detailed guide about this? or explain to me in layman's term. TIA.
ANSWERED!
Basically my problem was in this function given on the sample project of google places API..
BOOL SPEnsureGoogleAPIKey() {
BOOL userHasProvidedAPIKey = YES;
if (![kGoogleAPIKey isEqualToString:#"AIzaSyA2vs9pJoLrLs6XU8IRVHo7WxiuMufYXl8"]) {
userHasProvidedAPIKey = NO;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"API Key Needed" message:#"Please replace kGoogleAPIKey with your Google API key." delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[alert show];
}
return userHasProvidedAPIKey;
}
The if statement originally is incorrect that's why it always gives me the wrong value. now its working :) just added the not "!" in if
Related
I'm working on an iOS app and I created an UIViewController where I put my components and it works fine .
Now I'm trying to create a Custom UIView and to put my WebView and my SearchController into . I spent a lot of time without success .
Here is my .m file and I hope some one can help me with :
#import "HomeViewController.h"
#define widthtScreen [UIScreen mainScreen].bounds.size.width
#define heightScreen [UIScreen mainScreen].bounds.size.height
#interface HomeViewController () <UISearchResultsUpdating,UISearchBarDelegate,UIBarPositioningDelegate,UITableViewDataSource,UITableViewDelegate,MapWebViewDelegate>
#property(strong,nonatomic) MapWebView *webView;
#property (nonatomic) UIButton *btnGeolocate;
#property (nonatomic, strong) UISearchController *searchController;
#end
#implementation HomeViewController{
NSMutableArray *placesList;
BOOL isSearching;
}
-(void)loadView
{
[super loadView];
self.webView = [[MapWebView alloc] initWithFrame:CGRectMake(0, -100, widthtScreen, heightScreen+100)];
self.webView.mapWebViewDelegate = self;
[self.view addSubview:self.webView];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.navigationItem.hidesBackButton = YES;
mainDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
placesList = [[NSMutableArray alloc] init];
[self initializeSearchController];
mainDelegate.webView = self.webView;
self.btnGeolocate = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-75,550,60,60)];
self.btnGeolocate.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[self.btnGeolocate setBackgroundImage:[UIImage imageNamed:#"geo.png"]
forState:UIControlStateNormal];
[self.btnGeolocate addTarget:self action:#selector(btnGeolocatePressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.btnGeolocate];
mainDelegate.btnZoomIn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-80,620,30,30)];
mainDelegate.btnZoomIn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[mainDelegate.btnZoomIn setBackgroundColor:[UIColor blackColor]];
[mainDelegate.btnZoomIn addTarget:self action:#selector(btnZoomInPressed:) forControlEvents:UIControlEventTouchUpInside];
mainDelegate.btnZoomIn.tag=1;
UIImage *btnImage = [UIImage imageNamed:#"plus.png"];
[mainDelegate.btnZoomIn setImage:btnImage forState:UIControlStateNormal];
[self.view addSubview:mainDelegate.btnZoomIn];
mainDelegate.btnZoomOut = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-40,620,30,30)];
mainDelegate.btnZoomOut.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[mainDelegate.btnZoomOut setBackgroundColor:[UIColor blackColor]];
[mainDelegate.btnZoomOut addTarget:self action:#selector(btnZoomOutPressed:) forControlEvents:UIControlEventTouchUpInside];
mainDelegate.btnZoomOut.tag=1;
UIImage *btnImage2 = [UIImage imageNamed:#"minus.png"];
[mainDelegate.btnZoomOut setImage:btnImage2 forState:UIControlStateNormal];
[self.view addSubview:mainDelegate.btnZoomOut];
}
- (BOOL)slideNavigationControllerShouldDisplayLeftMenu
{
return YES;
}
- (BOOL)slideNavigationControllerShouldDisplayRightMenu
{
return YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"number :%lu",(unsigned long)[placesList count]);
return [placesList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
SuggestResultObject *sro = [SuggestResultObject new];
sro = [placesList objectAtIndex:indexPath.row];
cell.textLabel.text = sro.textPlace;
return cell;
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
self.navigationItem.leftBarButtonItem = nil;
self.navigationItem.rightBarButtonItem =nil;
return true;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.navigationItem.leftBarButtonItem = mainDelegate.leftBarButtonItem;
self.navigationItem.rightBarButtonItem = mainDelegate.rightBarButtonItem;
SuggestResultObject *sro = [SuggestResultObject new];
sro = [placesList objectAtIndex:indexPath.row];
self.searchController.active = false;
NSString *function = [[NSString alloc] initWithFormat: #"MobileManager.getInstance().moveToLocation(\"%#\",\"%#\")", sro.latPlace,sro.lonPlace];
[_webView evaluateJavaScript:function completionHandler:nil];
}
- (void)jsRun:(NSString *) searchText {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *function = [[NSString alloc] initWithFormat: #"MobileManager.getInstance().setSuggest(\"%#\")", searchText];
[_webView evaluateJavaScript:function completionHandler:nil];
});
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = YES;
}
- (void)initializeSearchController {
UITableViewController *searchResultsController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
searchResultsController.tableView.dataSource = self;
searchResultsController.tableView.delegate = self;
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
self.definesPresentationContext = YES;
self.searchController.hidesNavigationBarDuringPresentation = false;
self.searchController.accessibilityElementsHidden= true;
self.searchController.dimsBackgroundDuringPresentation = true;
self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
self.navigationItem.titleView = self.searchController.searchBar;
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.delegate = self;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
self.navigationItem.leftBarButtonItem = mainDelegate.leftBarButtonItem;
self.navigationItem.rightBarButtonItem = mainDelegate.rightBarButtonItem;
NSLog(#"Cancel clicked");
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
[placesList removeAllObjects];
}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
[placesList removeAllObjects];
if([searchController.searchBar.text length] != 0) {
isSearching = YES;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[self jsRun:searchController.searchBar.text];
}
else {
isSearching = NO;
[((UITableViewController *)self.searchController.searchResultsController).tableView reloadData];
}
}
-(void) btnGeolocatePressed : (id) sender{
}
-(void) btnZoomInPressed : (id) sender{
[_webView evaluateJavaScript:#"MobileManager.getInstance().zoomIn();" completionHandler:nil];
}
-(void) btnZoomOutPressed : (id) sender{
[_webView evaluateJavaScript:#"MobileManager.getInstance().zoomOut();" completionHandler:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)searchResult:(NSArray*)dataArray{
SuggestResultObject *sro = [SuggestResultObject new];
sro.textPlace = [dataArray objectAtIndex:0];
sro.lonPlace = [dataArray objectAtIndex:1];
sro.latPlace = [dataArray objectAtIndex:2];
[placesList addObject:sro];
[((UITableViewController *)self.searchController.searchResultsController).tableView reloadData];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
#end
Screenshots (Not sure how to scale images on stackoverflow.. OSX takes images in Retina format and they're fairly large! Sorry in advance!):
http://i.imgur.com/15qxDpc.png
http://i.imgur.com/QHduP07.png
How it works? Create a UIView and two sub-views: UITableView and
UIWebView. Constrain them properly.
Create the UISearchController with a nil SearchResultsController
as the parameter to the init method.
This lets the search controller know that the results will be
displayed in the current controller/view.
Next we setup the delegates for the UISearchController and create
the function for filtering.
Now that we have the view created, we need a UIViewController to
test it. We can either add the search bar to the tableView header OR
to the NavigationController if there is one..
Below, I have chosen to add it to the UINavigationController and I
told the UISearchController to NOT HIDE the navigation bar on
presentation.
That way, the results are displayed in the current view without hiding
the navigation bar.
You can then use the webview which is hidden and offscreen to do
whatever javascript searches you are using it for..
However, a better idea would be to use JSContext to execute
Javascript instead of a UIWebView. The advantage of the UIWebView
is that you can parse HTML and modify DOM which the JSContext
doesn't allow.
Anyway..
Here is the code I wrote for a UIView that contains a
UISearchController and a UIWebView.. and then to add it to a
UIViewController that is embedded in a UINavigationController.
//
// SearchView.h
// StackOverflow
//
// Created by Brandon T on 2016-06-26.
// Copyright © 2016 XIO. All rights reserved.
//
#import <UIKit/UIKit.h>
#class SearchView;
#protocol SearchViewDelegate <UISearchBarDelegate>
- (void)didSelectRowAtIndexPath:(SearchView *)searchView tableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath;
#end
#interface SearchView : UIView
#property (nonatomic, weak) id<SearchViewDelegate> delegate;
- (UISearchBar *)getSearchBar;
- (UIWebView *)getWebView;
#end
//
// SearchView.m
// StackOverflow
//
// Created by Brandon T on 2016-06-26.
// Copyright © 2016 XIO. All rights reserved.
//
#import "SearchView.h"
#define kTableViewCellIdentifier #"kTableViewCellIdentifier"
#interface SearchView() <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating>
#property (nonatomic, strong) UIWebView *webView;
#property (nonatomic, strong) UISearchController *searchController;
#property (nonatomic, strong) UITableView *tableView;
#property (nonatomic, strong) NSArray *dataSource;
#property (nonatomic, strong) NSArray *searchResults;
#end
#implementation SearchView
- (instancetype)init {
if (self = [super init]) {
[self setupData];
[self initControls];
[self themeControls];
[self registerCells];
[self doLayout];
}
return self;
}
- (UISearchBar *)getSearchBar {
return _searchController.searchBar;
}
- (UIWebView *)getWebView {
return _webView;
}
- (void)setDelegate:(id<SearchViewDelegate>)delegate {
_delegate = delegate;
_searchController.searchBar.delegate = delegate;
}
- (void)setupData {
//Begin fake data
_dataSource = #[#"Cat", #"Dog", #"Bird", #"Parrot", #"Rabbit", #"Racoon", #"Rat", #"Hamster", #"Pig", #"Cow"];
//End fake data
_searchResults = [_dataSource copy];
}
- (void)initControls {
_webView = [[UIWebView alloc] init];
_searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
_tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
}
- (void)themeControls {
[_webView setHidden:YES];
[_tableView setDelegate:self];
[_tableView setDataSource:self];
_searchController.searchResultsUpdater = self;
_searchController.dimsBackgroundDuringPresentation = false;
_searchController.definesPresentationContext = true;
_searchController.hidesNavigationBarDuringPresentation = false;
}
- (void)registerCells {
[_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kTableViewCellIdentifier];
}
- (void)doLayout {
[self addSubview:_webView];
[self addSubview:_tableView];
NSDictionary *views = #{#"webView":_webView, #"tableView": _tableView};
NSMutableArray *constraints = [[NSMutableArray alloc] init];
[constraints addObject:[NSString stringWithFormat:#"H:|-(%d)-[webView]-(%d)-|", 0, 0]];
[constraints addObject:[NSString stringWithFormat:#"H:|-(%d)-[tableView]-(%d)-|", 0, 0]];
[constraints addObject:[NSString stringWithFormat:#"V:|-(%d)-[webView(%d)]-(%d)-[tableView]-(%d)-|", -100, 100, 0, 0]];
for (NSString *constraint in constraints) {
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:constraint options:0 metrics:nil views:views]];
}
for (UIView *view in self.subviews) {
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _searchController.active && _searchController.searchBar.text.length > 0 ? [_searchResults count] : [_dataSource count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellIdentifier forIndexPath:indexPath];
if (_searchController.active && _searchController.searchBar.text.length > 0) {
cell.textLabel.text = _searchResults[indexPath.row];
}
else {
cell.textLabel.text = _dataSource[indexPath.row];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.delegate && [self.delegate respondsToSelector:#selector(didSelectRowAtIndexPath:tableView:indexPath:)]) {
[self.delegate didSelectRowAtIndexPath:self tableView:tableView indexPath:indexPath];
}
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
[self filterResults:searchController.searchBar.text scope:nil];
}
- (void)filterResults:(NSString *)searchText scope:(NSString *)scope {
_searchResults = [_dataSource filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
NSString *object = [evaluatedObject uppercaseString];
return [object rangeOfString:[searchText uppercaseString]].location != NSNotFound;
}]];
[_tableView reloadData];
}
#end
Then I tested it with the below UIViewController which is embedded in a UINavigationController..
//
// ViewController.m
// StackOverflow
//
// Created by Brandon T on 2016-06-26.
// Copyright © 2016 XIO. All rights reserved.
//
#import "ViewController.h"
#import "SearchView.h"
#interface ViewController ()<SearchViewDelegate>
#property (nonatomic, strong) SearchView *searchView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self initControls];
[self themeControls];
[self doLayout];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)initControls {
_searchView = [[SearchView alloc] init];
}
- (void)themeControls {
self.edgesForExtendedLayout = UIRectEdgeNone;
self.navigationItem.titleView = [_searchView getSearchBar];
[_searchView setDelegate:self];
}
- (void)doLayout {
[self.view addSubview:_searchView];
NSDictionary *views = #{#"searchView":_searchView};
NSMutableArray *constraints = [[NSMutableArray alloc] init];
[constraints addObject:[NSString stringWithFormat:#"H:|-%d-[searchView]-%d-|", 0, 0]];
[constraints addObject:[NSString stringWithFormat:#"V:|-%d-[searchView]-%d-|", 0, 0]];
for (NSString *constraint in constraints) {
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:constraint options:0 metrics:nil views:views]];
}
for (UIView *view in self.view.subviews) {
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
}
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
self.navigationItem.leftBarButtonItems = nil;
self.navigationItem.rightBarButtonItems = nil;
}
- (void)didSelectRowAtIndexPath:(SearchView *)searchView tableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
[[searchView getWebView] stringByEvaluatingJavaScriptFromString:#"SomeJavascriptHere"];
}
#end
I used UISearchController since learning that UISearchDisplayController is deprecated. But now have a problem, integrating with SPGooglePlacesAutocomplete forked library by Chenyuan in GitHub.
I get the search bar when I start typing no results are displayed. What I am also wondering is if UISearchDisplayController is deprecated how, come Chenyuan Demo run without warning or issue of deprecated methods.
Here is my code snippet which I attempted to convert his demo to UISearchController, please tell me where I'm going wrong.
MainViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
#class SPGooglePlacesAutocompleteQuery;
#interface MainViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate,
UISearchBarDelegate,
UISearchControllerDelegate,
UITableViewDataSource,
UITableViewDelegate>{
NSArray *searchResultPlaces;
SPGooglePlacesAutocompleteQuery *searchQuery;
MKPointAnnotation *selectedPlaceAnnotation;
BOOL shouldBeginEditing;
#private
CGRect _searchTableViewRect;
}
// Search
#property (strong, nonatomic) UISearchDisplayController *searchController;
#property (strong, nonatomic) MKLocalSearch *localSearch;
#property (strong, nonatomic) MKLocalSearchResponse *results;
#end
MainViewController.m snippet
// setup Search Controller
-(void) setupSearchController {
// The TableViewController used to display the results of a search
UITableViewController *searchResultsController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
searchResultsController.automaticallyAdjustsScrollViewInsets = NO; // Remove table view insets
searchResultsController.tableView.dataSource = self;
searchResultsController.tableView.delegate = self;
// Initialize our UISearchController
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
self.searchController.delegate = self;
self.searchController.searchBar.delegate = self;
// Hint for the search
self.searchController.searchBar.placeholder = #"Search your destination address";
}
// Setup Search Bar
-(void) setupSearchBar {
// Set search bar dimension and position
CGRect searchBarFrame = self.searchController.searchBar.frame;
CGRect viewFrame = self.view.frame;
self.searchController.searchBar.frame = CGRectMake(searchBarFrame.origin.x,
searchBarFrame.origin.y,
viewFrame.size.width,
44.0);
// Add SearchController's search bar to our view and bring it to front
[self.view addSubview:self.searchController.searchBar];
[self.view bringSubviewToFront:self.searchController.searchBar];
}
continuation of the MainViewController.m
-(void)willPresentSearchController:(UISearchController *)aSearchController {
aSearchController.searchBar.bounds = CGRectInset(aSearchController.searchBar.frame, 0.0f, 0.0f);
// Set the position of the result's table view below the status bar and search bar
// Use of instance variable to do it only once, otherwise it goes down at every search request
if (CGRectIsEmpty(_searchTableViewRect)) {
CGRect tableViewFrame = ((UITableViewController *)aSearchController.searchResultsController).tableView
.frame;
tableViewFrame.origin.y = tableViewFrame.origin.y + 64; //status bar (20) + nav bar (44)
tableViewFrame.size.height = tableViewFrame.size.height;
_searchTableViewRect = tableViewFrame;
}
[((UITableViewController *)aSearchController.searchResultsController).tableView setFrame:_searchTableViewRect];
}
#pragma mark -
#pragma mark UISearchDisplayDelegate
- (void)handleSearchForSearchString:(NSString *)searchString {
searchQuery.location = self.mapView.userLocation.coordinate;
searchQuery.input = searchString;
[searchQuery fetchPlaces:^(NSArray *places, NSError *error) {
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Could not fetch Places"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alert show];
} else {
searchResultPlaces = places;
// [self.searchController.searchResultsTableView reloadData];
[[(UITableViewController *)self.searchController.searchResultsController tableView] reloadData];
}
}];
}
- (BOOL)searchController:(UISearchController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self handleSearchForSearchString:searchString];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if (![searchBar isFirstResponder]) {
// User tapped the 'clear' button.
shouldBeginEditing = NO;
[self.searchController setActive:NO];
[self.mapView removeAnnotation:selectedPlaceAnnotation];
}
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
if (shouldBeginEditing) {
// Animate in the table view.
NSTimeInterval animationDuration = 0.3;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:animationDuration];
// self.searchController.searchResultsTableView.alpha = 0.75;
[(UITableViewController *)self.searchController.searchResultsController tableView].alpha = 0.75;
[UIView commitAnimations];
[self.searchController.searchBar setShowsCancelButton:YES animated:YES];
}
BOOL boolToReturn = shouldBeginEditing;
shouldBeginEditing = YES;
return boolToReturn;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [searchResultPlaces count];
}
- (SPGooglePlacesAutocompletePlace *)placeAtIndexPath:(NSIndexPath *)indexPath {
return searchResultPlaces[indexPath.row];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"SPGooglePlacesAutocompleteCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.font = [UIFont fontWithName:#"GillSans" size:16.0];
cell.textLabel.text = [self placeAtIndexPath:indexPath].name;
return cell;
}
#pragma mark -
#pragma mark UITableViewDelegate
- (void)recenterMapToPlacemark:(CLPlacemark *)placemark {
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.02;
span.longitudeDelta = 0.02;
region.span = span;
region.center = placemark.location.coordinate;
[self.mapView setRegion:region];
}
- (void)addPlacemarkAnnotationToMap:(CLPlacemark *)placemark addressString:(NSString *)address {
[self.mapView removeAnnotation:selectedPlaceAnnotation];
selectedPlaceAnnotation = [[MKPointAnnotation alloc] init];
selectedPlaceAnnotation.coordinate = placemark.location.coordinate;
selectedPlaceAnnotation.title = address;
[self.mapView addAnnotation:selectedPlaceAnnotation];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
SPGooglePlacesAutocompletePlace *place = [self placeAtIndexPath:indexPath];
[place resolveToPlacemark:^(CLPlacemark *placemark, NSString *addressString, NSError *error) {
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Could not map selected Place"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alert show];
} else if (placemark) {
[self addPlacemarkAnnotationToMap:placemark addressString:addressString];
[self recenterMapToPlacemark:placemark];
[self requestForwardGeoCoding:[self placeAtIndexPath:indexPath].name];
// ref: https://github.com/chenyuan/SPGooglePlacesAutocomplete/issues/10
[self.searchController setActive:NO];
// [self.searchController.searchResultsTableView deselectRowAtIndexPath:indexPath animated:NO];
}
}];
}
#end
You need to implement the UISearchResultsUpdating protocol.
#interface MainViewController : UIViewController <..., UISearchResultsUpdating>
.
.
.
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
// Filter results and reload table data
}
-(void) setupSearchController {
.
.
.
_searchController.searchResultsUpdater = self;
}
(as an aside, putting Google place results onto an Apple map is a violation of Google's terms of use, I believe).
i am newbie in iOS Development i want to Show multiple Annotation in MKMapViewController in iOS for that i write a code as in my viewDidLoad method
- (void)viewDidLoad
{
[super viewDidLoad];
self.mapView.delegate=self;
NSArray *name=[[NSArray alloc]initWithObjects:
#"VelaCherry",
#"Perungudi",
#"Tharamani", nil];
self.annotation=[[NSMutableArray alloc]initWithCapacity:[name count]];
MKPointAnnotation *mappin=[[MKPointAnnotation alloc]init];
CLLocationCoordinate2D location;
location.latitude=(double)12.970760345459;
location.longitude=(double)80.2190093994141;
mappin.coordinate=location;
mappin.title=[name objectAtIndex:0];
[self.annotation addObject:mappin];
location.latitude=(double)12.9752297537231;
location.longitude=(double)80.2313079833984;
mappin.coordinate=location;
mappin.title=[name objectAtIndex:1];
[self.annotation addObject:mappin];
location.latitude=(double)12.9788103103638;
location.longitude=(double)80.2412414550781;
mappin.title=[name objectAtIndex:2];
[self.annotation addObject:mappin];
[self.mapView addAnnotations:self.annotation];
self.mapView.mapType = MKMapTypeStandard;
self.mapView.showsUserLocation = YES;
}
But it is not show any of annotation in MKMapViewController please give me Solution for this.
I've written a demo app here which shows you one way to make your code a bit more cleaner and reusable, taking into account Paulw11's sugggestion.
Note, this method is purely done with code, no interface builder.
ViewController.h
#import <MapKit/MapKit.h>
#interface ViewController : UIViewController <MKMapViewDelegate>
#property (nonatomic, strong) MKMapView *mapView;
#end
ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self initViews];
[self initConstraints];
[self addAllPins];
}
-(void)initViews
{
self.mapView = [[MKMapView alloc] init];
self.mapView.delegate = self;
self.mapView.showsUserLocation = YES;
MKCoordinateRegion region = self.mapView.region;
region.center = CLLocationCoordinate2DMake(12.9752297537231, 80.2313079833984);
region.span.longitudeDelta /= 1.0; // Bigger the value, closer the map view
region.span.latitudeDelta /= 1.0;
[self.mapView setRegion:region animated:NO]; // Choose if you want animate or not
[self.view addSubview:self.mapView];
}
-(void)initConstraints
{
self.mapView.translatesAutoresizingMaskIntoConstraints = NO;
id views = #{
#"mapView": self.mapView
};
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[mapView]|" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[mapView]|" options:0 metrics:nil views:views]];
}
-(void)addAllPins
{
self.mapView.delegate=self;
NSArray *name=[[NSArray alloc]initWithObjects:
#"VelaCherry",
#"Perungudi",
#"Tharamani", nil];
NSMutableArray *arrCoordinateStr = [[NSMutableArray alloc] initWithCapacity:name.count];
[arrCoordinateStr addObject:#"12.970760345459, 80.2190093994141"];
[arrCoordinateStr addObject:#"12.9752297537231, 80.2313079833984"];
[arrCoordinateStr addObject:#"12.9788103103638, 80.2412414550781"];
for(int i = 0; i < name.count; i++)
{
[self addPinWithTitle:name[i] AndCoordinate:arrCoordinateStr[i]];
}
}
-(void)addPinWithTitle:(NSString *)title AndCoordinate:(NSString *)strCoordinate
{
MKPointAnnotation *mapPin = [[MKPointAnnotation alloc] init];
// clear out any white space
strCoordinate = [strCoordinate stringByReplacingOccurrencesOfString:#" " withString:#""];
// convert string into actual latitude and longitude values
NSArray *components = [strCoordinate componentsSeparatedByString:#","];
double latitude = [components[0] doubleValue];
double longitude = [components[1] doubleValue];
// setup the map pin with all data and add to map view
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
mapPin.title = title;
mapPin.coordinate = coordinate;
[self.mapView addAnnotation:mapPin];
}
If you zoom out a little, you'll see all three pins:
You should use the function CLLocationCoordinate2DMake to initialise your location objects in a single line. More importantly you need to allocate a new annotation object for each annotation -
- (void)viewDidLoad
{
[super viewDidLoad];
self.mapView.delegate=self;
NSArray *name=[[NSArray alloc]initWithObjects:
#"VelaCherry",
#"Perungudi",
#"Tharamani", nil];
self.annotation=[[NSMutableArray alloc]initWithCapacity:[name count]];
MKPointAnnotation *mappin;
CLLocationCoordinate2D location;
location = CLLocationCoordinate2DMake(12.970760345459,80.2190093994141);
mappin = [[MKPointAnnotation alloc]init];
mappin.coordinate=location;
mappin.title=[name objectAtIndex:0];
[self.annotation addObject:mappin];
mappin = [[MKPointAnnotation alloc]init];
location = CLLocationCoordinate2DMake(12.9752297537231,80.2313079833984);
mappin.coordinate=location;
mappin.title=[name objectAtIndex:1];
[self.annotation addObject:mappin];
mappin = [[MKPointAnnotation alloc]init];
location = CLLocationCoordinate2DMake(12.9788103103638,80.2412414550781);
mappin.coordinate=location;
mappin.title=[name objectAtIndex:2];
[self.annotation addObject:mappin];
[self.mapView addAnnotations:self.annotation];
self.mapView.mapType = MKMapTypeStandard;
self.mapView.showsUserLocation = YES;
}
//
// MyAnnotation.h
// SimpleMapView
//
// Created by Mayur Birari.
//
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface MyAnnotation : NSObject<MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString* title;
NSString* subtitle;
}
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, copy) NSString* title;
#property (nonatomic, copy) NSString* subtitle;
#end
//
// MyAnnotation.m
// SimpleMapView
//
// Created by Mayur Birari .
//
#import "MyAnnotation.h"
#implementation MyAnnotation
#synthesize title;
#synthesize subtitle;
#synthesize coordinate;
- (void)dealloc
{
[super dealloc];
self.title = nil;
self.subtitle = nil;
}
#end
//
// RootViewController.h
// SimpleMapView
//
// Created by Mayur Birari.
//
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import "UserProfileVC.h"
#interface RootViewController : UIViewController<MKMapViewDelegate> {
IBOutlet MKMapView* mapView;
IBOutlet UserProfileVC* userProfileVC;
}
#property(nonatomic,retain) IBOutlet MKMapView* mapView;
#property(nonatomic,retain) IBOutlet UserProfileVC* userProfileVC;
#end
//
// RootViewController.m
// SimpleMapView
//
// Created by Mayur Birari.
//
#import "RootViewController.h"
#import "MyAnnotation.h"
#import "UserProfileVC.h"
#implementation RootViewController
#synthesize mapView,userProfileVC;
#pragma mark -
#pragma mark View lifecycle
- (void)gotoLocation
{
// start off by default in San Francisco
MKCoordinateRegion newRegion;
newRegion.center.latitude = 37.786996;
newRegion.center.longitude = -122.440100;
newRegion.span.latitudeDelta = 0.112872;
newRegion.span.longitudeDelta = 0.109863;
[self.mapView setRegion:newRegion animated:YES];
}
- (void)viewDidLoad {
[super viewDidLoad];
CLLocation *userLoc = mapView.userLocation.location;
CLLocationCoordinate2D userCoordinate = userLoc.coordinate;
NSLog(#"user latitude = %f",userCoordinate.latitude);
NSLog(#"user longitude = %f",userCoordinate.longitude);
mapView.delegate=self;
NSMutableArray* annotations=[[NSMutableArray alloc] init];
CLLocationCoordinate2D theCoordinate1;
theCoordinate1.latitude = 37.786996;
theCoordinate1.longitude = -122.419281;
CLLocationCoordinate2D theCoordinate2;
theCoordinate2.latitude = 37.810000;
theCoordinate2.longitude = -122.477989;
CLLocationCoordinate2D theCoordinate3;
theCoordinate3.latitude = 37.760000;
theCoordinate3.longitude = -122.447989;
CLLocationCoordinate2D theCoordinate4;
theCoordinate4.latitude = 37.80000;
theCoordinate4.longitude = -122.407989;
MyAnnotation* myAnnotation1=[[MyAnnotation alloc] init];
myAnnotation1.coordinate=theCoordinate1;
myAnnotation1.title=#"Rohan";
myAnnotation1.subtitle=#"in the city";
MyAnnotation* myAnnotation2=[[MyAnnotation alloc] init];
myAnnotation2.coordinate=theCoordinate2;
myAnnotation2.title=#"Vaibhav";
myAnnotation2.subtitle=#"on a Bridge";
MyAnnotation* myAnnotation3=[[MyAnnotation alloc] init];
myAnnotation3.coordinate=theCoordinate3;
myAnnotation3.title=#"Rituraaj";
myAnnotation3.subtitle=#"in the forest";
MyAnnotation* myAnnotation4=[[MyAnnotation alloc] init];
myAnnotation4.coordinate=theCoordinate4;
myAnnotation4.title=#"Amit";
myAnnotation4.subtitle=#"at Russian Hill";
[mapView addAnnotation:myAnnotation1];
[mapView addAnnotation:myAnnotation2];
[mapView addAnnotation:myAnnotation3];
[mapView addAnnotation:myAnnotation4];
[annotations addObject:myAnnotation1];
[annotations addObject:myAnnotation2];
[annotations addObject:myAnnotation3];
[annotations addObject:myAnnotation4];
NSLog(#"%d",[annotations count]);
//[self gotoLocation];//to catch perticular area on screen
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
// Walk the list of overlays and annotations and create a MKMapRect that
// bounds all of them and store it into flyTo.
MKMapRect flyTo = MKMapRectNull;
for (id <MKAnnotation> annotation in annotations) {
NSLog(#"fly to on");
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
//NSLog(#"else-%#",annotationPoint.x);
}
}
// Position the map so that all overlays and annotations are visible on screen.
mapView.visibleMapRect = flyTo;
UIBarButtonItem* temp=[[UIBarButtonItem alloc] init];
temp.title=#"Back";
self.navigationItem.backBarButtonItem=temp;
[temp release];
}
/*
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait || UIInterfaceOrientationLandscapeLeft || UIInterfaceOrientationLandscapeRight);
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 0;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
*/
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
#pragma mark MKMapViewDelegate
/*
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
return [kml viewForOverlay:overlay];
}
*/
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
NSLog(#"welcome into the map view annotation");
// if it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
// try to dequeue an existing pin view first
static NSString* AnnotationIdentifier = #"AnnotationIdentifier";
MKPinAnnotationView* pinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
pinView.animatesDrop=YES;
pinView.canShowCallout=YES;
pinView.pinColor=MKPinAnnotationColorPurple;
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
[rightButton addTarget:self
action:#selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = rightButton;
UIImageView *profileIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"profile.png"]];
pinView.leftCalloutAccessoryView = profileIconView;
[profileIconView release];
return pinView;
}
-(IBAction)showDetails:(id)sender{
NSLog(#"Annotation Click");
self.userProfileVC.title=((UIButton*)sender).currentTitle;
[self.navigationController pushViewController:self.userProfileVC animated:YES];
}
- (void)dealloc {
[super dealloc];
}
#end
I would like to add a custom image button into the callout of annotations in specific locations. For example searching for starbucks would bring up an annotation marker for starbucks locations, and when the marker is pressed the callout will display a button that then will direct you to another viewcontroller with starbucks information. Right now the annotation displays the address of the location when pressed, how would I change this to displaying a button at custom locations of my choosing? I am very new to xcode and cannot seem to find much helpful information to this relative to how I have designed my app so far. Everything is function as desired except for the fact I do not know where to start to add a button.
here are my ViewControllers
#import "ViewController.h"
#interface ViewController () <UISearchDisplayDelegate, UISearchBarDelegate>
#end
#implementation ViewController {
MKLocalSearch *localSearch;
MKLocalSearchResponse *results;
}
#pragma mark - View Lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
[self.searchDisplayController setDelegate:self];
[self.ibSearchBar setDelegate:self];
// Zoom the map to current location.
[self.ibMapView setShowsUserLocation:YES];
[self.ibMapView setUserInteractionEnabled:YES];
[self.ibMapView setUserTrackingMode:MKUserTrackingModeFollow];
}
#pragma mark - Search Methods
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
// Cancel any previous searches.
[localSearch cancel];
// Perform a new search.
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = searchBar.text;
request.region = self.ibMapView.region;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error){
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if (error != nil) {
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Map Error",nil)
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK",nil) otherButtonTitles:nil] show];
return;
}
if ([response.mapItems count] == 0) {
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"No Results",nil)
message:nil
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK",nil) otherButtonTitles:nil] show];
return;
}
results = response;
[self.searchDisplayController.searchResultsTableView reloadData];
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [results.mapItems count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *IDENTIFIER = #"SearchResultsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:IDENTIFIER];
}
MKMapItem *item = results.mapItems[indexPath.row];
cell.textLabel.text = item.name;
cell.detailTextLabel.text = item.placemark.addressDictionary[#"Street"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.searchDisplayController setActive:NO animated:YES];
MKMapItem *item = results.mapItems[indexPath.row];
[self.ibMapView addAnnotation:item.placemark];
[self.ibMapView selectAnnotation:item.placemark animated:NO];
[self.ibMapView setCenterCoordinate:item.placemark.location.coordinate animated:YES];
[self.ibMapView setUserTrackingMode:MKUserTrackingModeNone];
}
#end
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface ViewController : UIViewController
#property (strong, nonatomic) IBOutlet UISearchBar *ibSearchBar;
#property (strong, nonatomic) IBOutlet MKMapView *ibMapView;
#end
You could set a button as the callout accessory view ,in the viewForAnnotation method:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
static NSString *AnnotationIdentifier = #"Annotation";
if ([annotation isKindOfClass:MKUserLocation.class]) {
return nil;
}
MKPinAnnotationView* pinAnnotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
if (!pinAnnotationView)
{
pinAnnotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] ;
pinAnnotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
pinAnnotationView.canShowCallout = YES;
}
return pinAnnotationView;
}
then you can use the mapView:annotationView:calloutAccessoryControlTapped delegate method to respond when users tap a callout view’s control and, in this case, redirect to another view controller:
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
InfoController *infoController = [[InfoController alloc] initWithNibName:#"InfoController" bundle:[NSBundle mainBundle]];
/*
here you can pass the necessary information to your InfoController
*/
[self.navigationController pushViewController:infoController animated:YES];
[infoController release];
}
In this example I take usage of a UINavigationController to manage navigation through my view controllers.
There are great resources on SO on how to customize the callout view, like here and here. You can also look at Apple's Documentation for MKAnnotationView, especially the subclassing notes and their MapCallouts example.
I have a root view controller which composes a search bar on the top and a child table view controller on the bottom. I used composition instead of assigning the search bar to the table view's header for these reasons:
I didn't want the index to overlap with the search bar (like Contacts app).
I wanted the search bar to be sticky. That is, it doesn't move when I scroll the table view (again like the Contacts app).
My table view already had a header.
Since the search bar is in the root view controller, I instantiate my search display controller in the root view controller also. There are two problems with the search UI for which I seek advice:
The translucent gray overlay does not cover the entire child table view. It leaves the top portion of the header and the index visible.
Likewise, the search results table does not cover the entirety of the child table view. I know how to manually change the frame of this results table view, but doing so only fixes just that ... the gray translucent overlay's frame is not linked to the results table view frame. Their is no property to access the overlay.
1) Idle
2) Enter Search Bar
3) Start Typing
#import "ContactsRootViewController.h"
#import "ContactsViewController.h"
#import "UIView+position.h"
#import "User.h"
#import "UserCellView.h"
#import "UserViewController.h"
#interface ContactsRootViewController ()
#property(nonatomic, strong) UISearchBar* searchBar;
#property(nonatomic, strong) ContactsViewController* contactsViewController;
#property(nonatomic, strong) UISearchDisplayController* searchController;
#property(nonatomic, strong) NSMutableArray* matchedUsers;
#end
#implementation ContactsRootViewController
#pragma mark UIViewController
- (NSString*)title
{
return #"Contacts";
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.matchedUsers = [NSMutableArray array];
self.searchBar = [[UISearchBar alloc] init];
self.searchBar.placeholder = #"Search";
[self.searchBar sizeToFit];
[self.view addSubview:self.searchBar];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if (self.contactsViewController == nil) {
self.contactsViewController = [[ContactsViewController alloc] init];
[self addChildViewController:self.contactsViewController];
self.contactsViewController.view.frame = CGRectMake(
0.0,
self.searchBar.bottomY,
self.view.frame.size.width,
self.view.frame.size.height - self.searchBar.bottomY
);
self.contactsViewController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
[self.view addSubview:self.contactsViewController.view];
[self.contactsViewController didMoveToParentViewController:self];
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self.contactsViewController];
self.searchController.delegate = self;
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
}
}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.matchedUsers.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* identifier = #"contactsRootViewUserCell";
UserCellView* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UserCellView alloc] initWithIdentifier:identifier];
}
cell.user = [self.matchedUsers objectAtIndex:indexPath.row];
return cell;
}
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.navigationController pushViewController:[[UserViewController alloc] initWithUser:[self.matchedUsers objectAtIndex:indexPath.row]] animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [UserCellView height];
}
#pragma mark UISearchDisplayControllerDelegate
- (BOOL)searchDisplayController:(UISearchDisplayController*)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self.matchedUsers removeAllObjects];
searchString = [searchString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (searchString.length > 0) {
for (User* user in self.contactsViewController.allUsers) {
NSRange match = [user.userDisplayName rangeOfString:searchString options:NSCaseInsensitiveSearch];
if (match.location != NSNotFound) {
[self.matchedUsers addObject:user];
}
}
}
return YES;
}
- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
[self.searchBar resignFirstResponder];
}
#end
I re-implemented UISearchDisplayController, calling my implementation SearchController. It does the same thing and has similar delegate callbacks, but the frame of the search results can be controlled by the programmer.
Header
#import <Foundation/Foundation.h>
#class SearchController;
#protocol SearchControllerDelegate <NSObject>
#required
- (BOOL)searchController:(SearchController*)controller shouldReloadTableForSearchString:(NSString*)searchText;
#optional
- (void)searchController:(SearchController*)controller didShowSearchResultsTableView:(UITableView*)tableView;
- (void)searchController:(SearchController *)controller didHideSearchResultsTableView:(UITableView *)tableView;
- (void)searchControllerDidBeginSearch:(SearchController*)controller;
- (void)searchControllerDidEndSearch:(SearchController*)controller;
#end
#interface SearchController : UIViewController <UISearchBarDelegate>
#property(nonatomic, weak) NSObject<SearchControllerDelegate>* delegate;
#property(nonatomic, weak) NSObject<UITableViewDataSource>* searchResultsDataSource;
#property(nonatomic, weak) NSObject<UITableViewDelegate>* searchResultsDelegate;
#property(nonatomic, strong, readonly) UITableView* searchResultsTableView;
- (id)initWithSearchBar:(UISearchBar*)searchBar;
#end
Implementation
#import "SearchController.h"
#import "UIView+position.h"
#interface SearchController ()
#property(nonatomic, strong) UISearchBar* searchBar;
#property(nonatomic, strong) UIButton* searchResultsVeil;
#property(nonatomic, strong, readwrite) UITableView* searchResultsTableView;
#property(nonatomic, assign) BOOL searchResultsTableViewHidden;
- (void)didTapSearchResultsVeil;
- (void)hideSearchResults;
#end
#implementation SearchController
#pragma mark UIViewController
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.searchResultsTableView deselectRowAtIndexPath:[self.searchResultsTableView indexPathForSelectedRow] animated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.userInteractionEnabled = NO;
}
#pragma mark SearchController ()
- (void)hideSearchResults
{
self.searchBar.text = nil;
[self.searchResultsTableView reloadData];
self.searchResultsTableViewHidden = YES;
[self.searchBar resignFirstResponder];
}
- (void)didTapSearchResultsVeil
{
[self hideSearchResults];
}
- (void)setSearchResultsTableViewHidden:(BOOL)searchResultsTableViewHidden
{
if (self.searchResultsTableView != nil) {
if (self.searchResultsTableView.hidden && !searchResultsTableViewHidden) {
self.searchResultsTableView.hidden = searchResultsTableViewHidden;
if ([self.delegate respondsToSelector:#selector(searchController:didShowSearchResultsTableView:)]) {
[self.delegate searchController:self didShowSearchResultsTableView:self.searchResultsTableView];
}
} else if (!self.searchResultsTableView.hidden && searchResultsTableViewHidden) {
self.searchResultsTableView.hidden = searchResultsTableViewHidden;
if ([self.delegate respondsToSelector:#selector(searchController:didHideSearchResultsTableView:)]) {
[self.delegate searchController:self didHideSearchResultsTableView:self.searchResultsTableView];
}
}
}
}
- (BOOL)searchResultsTableViewHidden
{
return self.searchResultsTableView == nil || self.searchResultsTableView.hidden;
}
#pragma mark SearchController
- (id)initWithSearchBar:(UISearchBar *)searchBar
{
if (self = [super init]) {
self.searchBar = searchBar;
self.searchBar.delegate = self;
}
return self;
}
- (void)setSearchResultsDataSource:(NSObject<UITableViewDataSource> *)searchResultsDataSource
{
_searchResultsDataSource = searchResultsDataSource;
if (self.searchResultsTableView != nil) {
self.searchResultsTableView.dataSource = searchResultsDataSource;
}
}
- (void)setSearchResultsDelegate:(NSObject<UITableViewDelegate> *)searchResultsDelegate
{
_searchResultsDelegate = searchResultsDelegate;
if (self.searchResultsTableView != nil) {
self.searchResultsTableView.delegate = searchResultsDelegate;
}
}
#pragma mark UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if ([self.delegate searchController:self shouldReloadTableForSearchString:searchText]) {
[self.searchResultsTableView reloadData];
self.searchResultsTableViewHidden = [self.searchResultsTableView.dataSource tableView:self.searchResultsTableView numberOfRowsInSection:0] == 0;
}
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:YES animated:YES];
if (self.searchResultsVeil == nil) {
self.searchResultsVeil = [[UIButton alloc] initWithFrame:self.view.bounds];
self.searchResultsVeil.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.6];
self.searchResultsVeil.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.searchResultsVeil addTarget:self action:#selector(didTapSearchResultsVeil) forControlEvents:UIControlEventTouchUpInside];
self.searchResultsTableView = [[UITableView alloc] initWithFrame:self.searchResultsVeil.bounds style:UITableViewStylePlain];
self.searchResultsTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
if ([self.searchResultsTableView respondsToSelector:#selector(setSeparatorInset:)]) {
self.searchResultsTableView.separatorInset = UIEdgeInsetsMake(
0.0,
self.searchResultsTableView.width,
0.0,
0.0
);
}
self.searchResultsTableViewHidden = YES;
if (self.searchResultsDataSource != nil) {
self.searchResultsTableView.dataSource = self.searchResultsDataSource;
}
if (self.searchResultsDelegate != nil) {
self.searchResultsTableView.delegate = self.searchResultsDelegate;
}
[self.view addSubview:self.searchResultsVeil];
[self.searchResultsVeil addSubview:self.searchResultsTableView];
}
self.view.userInteractionEnabled = YES;
self.searchResultsVeil.hidden = NO;
if ([self.delegate respondsToSelector:#selector(searchControllerDidBeginSearch:)]) {
[self.delegate searchControllerDidBeginSearch:self];
}
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:NO animated:YES];
self.view.userInteractionEnabled = NO;
self.searchResultsVeil.hidden = YES;
if ([self.delegate respondsToSelector:#selector(searchControllerDidEndSearch:)]) {
[self.delegate searchControllerDidEndSearch:self];
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[self hideSearchResults];
}
#end
Usage
self.searchController = [[SearchController alloc] initWithSearchBar:self.searchBar];
self.searchController.delegate = self;
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
[self addChildViewController:self.searchController];
self.searchController.view.frame = CGRectMake(
self.searchBar.x,
self.searchBar.bottomY,
self.searchBar.width,
self.view.height - self.searchBar.bottomY
);
[self.view addSubview:self.searchController.view];
[self.searchController didMoveToParentViewController:self];
It looks like your view controller does not define a presentation context. I had a similar problem and was able to resolve it by setting
self.definesPresentationContext = YES;
in viewDidLoad. According to the documentation this property is
A Boolean value that indicates whether this view controller's view is covered when the view controller or one of its descendants presents a view controller.