// // RailSearchAddressVC.m // tongxin // // Created by WeiChaoZheng on 2018/11/10. // Copyright © 2018年 xTT. All rights reserved. // #import "RailSearchAddressVC.h" #import "RailAddressTableViewCell.h" #define SearchHistroySaveCount 5 @interface RailSearchAddressVC () @property (nonatomic, strong) AMapSearchAPI *search; @property (nonatomic, strong) AMapInputTipsSearchRequest *currentRequest; /** 历史搜索数据 */ @property (nonatomic, strong) NSMutableArray *historyData; /** 是否是历史记录的模式 */ @property (nonatomic, assign) BOOL isHistory; /** 搜索栏 */ @property (strong, nonatomic) UISearchBar *searchBar; @end @implementation RailSearchAddressVC @synthesize myDataSource = _myDataSource; - (NSMutableArray *)myDataSource{ if (!_myDataSource) { _myDataSource = [NSMutableArray array] ; } return _myDataSource; } -(UIImage *)imageWithColor:(UIColor *)color { CGRect rect = CGRectMake(0, 0, 1, 1); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; self.navigationController.navigationBar.translucent = NO; [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:RGB(176, 176, 176)] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault]; [self.navigationController.navigationBar setShadowImage:[self imageWithColor:RGB(176, 176, 176)]]; } -(void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; } - (void)viewDidLoad { [super viewDidLoad]; //初始化搜索 self.search = [[AMapSearchAPI alloc] init]; self.search.delegate = self; UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth-42-8, 36)]; _searchBar = [[UISearchBar alloc] initWithFrame:titleView.bounds]; _searchBar.delegate = self; [_searchBar setTintColor:[UIColor redColor]]; [_searchBar setPlaceholder:@"请输入搜索地址"]; [titleView addSubview:_searchBar]; self.navigationItem.titleView = titleView; //注册cell [self.myTableView registerNib:[UINib nibWithNibName:@"RailAddressTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"RailAddressTableViewCellID"]; //去线 self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone; [self.view addSubview: self.myTableView]; } //MARK: -----搜索框 UISearchBarDelegate ----- - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{ xLog(@"aasdads"); } - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{ self.isHistory = YES; [self.myDataSource removeAllObjects]; // 显示 myTableView 显示历史搜索记录 if([UserDefaults valueForKey:SearchHistory]){ // 把字典转换成 模型类 NSArray *tempArr = [UserDefaults valueForKey:SearchHistory]; NSMutableArray *arr = [NSMutableArray array]; for (int i = 0 ; i < tempArr.count; i++) { AMapTip *model = [AMapTip mj_objectWithKeyValues:tempArr[i]]; [arr addObject:model]; } self.historyData = [[NSMutableArray alloc] initWithArray:@[arr]]; self.myDataSource = self.historyData; } [self.myTableView reloadData]; return YES; } -(BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ NSString *str = searchBar.text; NSString *resultStr = [str stringByReplacingCharactersInRange:range withString:text]; [self searchRequestString:resultStr]; return YES; } -(void)searchRequestString:(NSString *)str{ //搜索的信息 AMapInputTipsSearchRequest *request = [AMapInputTipsSearchRequest new]; request.keywords = str; self.currentRequest = request; //调起检索 [self.search AMapInputTipsSearch:request]; self.isHistory = NO; } //MARK: ---- 高德 搜索 API 代理方法 ---- -(void) AMapSearchRequest:(id)request didFailWithError:(NSError *)error{ xLog(@"Search Error: %@",error.description); } -(void) onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response{ if (self.currentRequest == nil || self.currentRequest != request ){ return; } if (response.count == 0){ return; } [self.myDataSource removeAllObjects]; //过滤掉location也为空的 查询结果 比如: 天津市 // NSMutableArray *tempArr = [NSMutableArray array]; for (AMapTip* item in response.tips) { if(item.location){ [tempArr addObject:item]; } } [self.myDataSource addObjectsFromArray:@[tempArr]]; [self.myTableView setHidden:NO]; [self.myTableView reloadData]; } //MARK: 清除 历史轨迹的搜索记录 -(void)clearHistroyAction{ [UserDefaults removeObjectForKey:SearchHistory]; [UserDefaults synchronize]; [self.historyData removeAllObjects]; self.isHistory = YES; self.myDataSource = self.historyData; [self.myTableView reloadData]; } //MARK: 存进历史轨迹记录 -(void)saveHistorySearch:(AMapTip*)tip{ NSDictionary *dic = [tip mj_keyValues]; NSMutableArray * arr; if([UserDefaults valueForKey:SearchHistory]){ arr = [[NSMutableArray alloc] initWithArray:[UserDefaults valueForKey:SearchHistory]]; int tempIndex = -1; for (int i = 0; i < arr.count; i++) { NSString *uid = arr[i][@"uid"]; if([tip.uid isEqualToString:uid]){ tempIndex = i; } } if(tempIndex >= 0){ // 存在历史记录中的 //移到第一位 [arr removeObjectAtIndex:tempIndex]; [arr insertObject:dic atIndex:0]; }else{ //不存在的 if(arr.count == SearchHistroySaveCount){ [arr insertObject:dic atIndex:0]; [arr removeLastObject]; }else{ [arr insertObject:dic atIndex:0]; } } }else{ arr = [NSMutableArray array]; [arr addObject:dic]; } [UserDefaults setValue:arr forKey:SearchHistory]; [UserDefaults synchronize]; } -(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ if(section == 0){ if(self.isHistory){ UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 30)]; view.backgroundColor = [UIColor whiteColor]; UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(14, (30-21)/2, 100, 21)]; label.font = [UIFont systemFontOfSize:15]; label.textColor = RGB(51, 51, 51 ); label.text = @"搜索记录"; [view addSubview: label]; UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(ScreenWidth-30, 0, 30 , 30); [button setImage:[UIImage imageNamed:@"icon_delect_search_grey"] forState:0]; [button addTarget:self action:@selector(clearHistroyAction) forControlEvents:UIControlEventTouchUpInside]; [view addSubview: button]; return view; } return nil; }else{ return nil; } } -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{ if(section == 0){ if(self.isHistory){ return 30; } return 0.01; }else{ return 0.01; } } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ RailAddressTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RailAddressTableViewCellID" forIndexPath:indexPath]; AMapTip * model = self.myDataSource[indexPath.section][indexPath.row]; cell.aTitleLabel.text = model.name; cell.model = model; return cell; } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ AMapTip * model = self.myDataSource[indexPath.section][indexPath.row]; if(self.isHistory){ [self searchRequestString:model.name]; [self.searchBar becomeFirstResponder]; self.searchBar.text = model.name; self.isHistory = NO; [self.myTableView reloadData]; }else{ //存进搜索历史记录 [self saveHistorySearch:model]; if(self.selectAddressCallBack){ self.selectAddressCallBack(model.name, model.location); } [self.navigationController popViewControllerAnimated:YES]; } } -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ [self.searchBar resignFirstResponder]; } @end