Advertisement
Guest User

Untitled

a guest
Jul 21st, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.94 KB | None | 0 0
  1. - (void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope
  2. {
  3. NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", searchText];;
  4.  
  5.  
  6. //activities is table that contains my objects that I display their contents in the table
  7. self.filteredData = [activities filteredArrayUsingPredicate:resultPredicate];
  8. }
  9.  
  10. - (BOOL)searchDisplayController:(UISearchDisplayController *)controller
  11. shouldReloadTableForSearchScope:(NSInteger)searchOption
  12. {
  13. [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
  14. [[self.searchDisplayController.searchBar scopeButtonTitles]
  15. objectAtIndex:searchOption]];
  16.  
  17. // Return YES to cause the search result table view to be reloaded.
  18. return YES;
  19. }
  20. //activite is my object that I use to desplay its attribut in table
  21. IPADActivity *activite ;
  22. if (ThetableView == self.searchDisplayController.searchResultsTableView) {
  23. activite = [self.filteredData objectAtIndex:indexPath.row];
  24.  
  25.  
  26. }
  27. else{
  28. activite = [[objects
  29. objectForKey:[objectsIndex objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
  30. }
  31.  
  32. //
  33. // ViewController.m
  34. // SearchTut
  35. //
  36.  
  37.  
  38. #import "ViewController.h"
  39. #import "SearchTableCell.h"
  40. #import "XMLReader.h"
  41.  
  42. @interface ViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>
  43.  
  44. @property (weak, nonatomic) IBOutlet UITableView *tablView;
  45. @property (weak, nonatomic) IBOutlet UISearchBar *searchBr;
  46.  
  47. @property (nonatomic, strong) NSMutableArray *arrayList; //main table array
  48. @property (nonatomic, strong) NSMutableArray *arrayFilteredList; //array with search results while user types in search bar
  49. @property (nonatomic, strong) NSMutableDictionary *dictList; //need to manufacture an equivalent dictionary like below from the json array
  50. /*
  51. @{
  52. @"B" : @[@"Bear", @"Black Swan", @"Buffalo"],
  53. @"C" : @[@"Camel", @"Cockatoo"],
  54. @"D" : @[@"Dog", @"Donkey"],
  55. @"E" : @[@"Emu"],
  56. @"G" : @[@"Giraffe", @"Greater Rhea"],
  57. @"H" : @[@"Hippopotamus", @"Horse"],
  58. @"K" : @[@"Koala"],
  59. @"L" : @[@"Lion", @"Llama"],
  60. @"M" : @[@"Manatus", @"Meerkat"],
  61. @"P" : @[@"Panda", @"Peacock", @"Pig", @"Platypus", @"Polar Bear"],
  62. @"R" : @[@"Rhinoceros"],
  63. @"S" : @[@"Seagull"],
  64. @"T" : @[@"Tasmania Devil"],
  65. @"W" : @[@"Whale", @"Whale Shark", @"Wombat"]
  66. };
  67. Refer: https://www.appcoda.com/ios-programming-index-list-uitableview/
  68. */
  69.  
  70. @property (nonatomic, strong) NSMutableDictionary *dictListFiltered; //dictionary when searched
  71. @property (nonatomic, assign) BOOL isFiltered; //If user starts entering text in search bar, this flag is YES. If there is no text in search bar, this flag is NO.
  72.  
  73. @end
  74.  
  75. @implementation ViewController
  76.  
  77. - (void)viewDidLoad {
  78. [super viewDidLoad];
  79. // Initialisers
  80. self.tablView.dataSource = self;
  81. self.tablView.delegate = self;
  82. self.searchBr.delegate = self;
  83. self.arrayList = [NSMutableArray array];
  84. self.dictList = [NSMutableDictionary dictionary];
  85. self.dictListFiltered = [NSMutableDictionary dictionary];
  86. self.isFiltered = NO;
  87.  
  88. //Get and parse XML from file and load the result in array
  89. NSString *strXMLPath = [[NSBundle mainBundle] pathForResource:@"List" ofType:@"xml"];
  90. NSError *error;
  91. NSString *strXML = [NSString stringWithContentsOfFile:strXMLPath encoding:NSUTF8StringEncoding error:&error];
  92. NSDictionary *dict = [XMLReader dictionaryForXMLString:strXML error:&error];
  93. NSDictionary *dictPriceList = [dict objectForKey:@"PRICELIST"];
  94. NSArray *arrayLine = [dictPriceList objectForKey:@"LINE"];
  95. NSMutableArray *arrayTempPriceList = [NSMutableArray array];
  96. for (NSDictionary *dict in arrayLine) {
  97. [arrayTempPriceList addObject:dict];
  98. }
  99. self.arrayList = arrayTempPriceList;
  100. NSLog(@"%@", self.arrayList);
  101.  
  102. //Create dictionary for sectioned table grouped with respect to PRICELISTCATEGORY value. PRICELISTCATEGORY value will be set in the section title. Logic to group table in sections is below
  103. [self groupXMLinSectionsWithArray:arrayTempPriceList];
  104. }
  105.  
  106. - (void)groupXMLinSectionsWithArray:(NSMutableArray *)arrayJson {
  107. if (arrayJson.count > 0) { //added this condition to reset json during search.
  108. for (NSDictionary *dict in arrayJson ) {
  109. NSString *strPriceListCategory = [[dict objectForKey:@"PRICELISTCATEGORY"] objectForKey:@"text"];
  110. if (self.isFiltered) {
  111. if ([[self.dictListFiltered allKeys] containsObject:strPriceListCategory]) {
  112. NSMutableArray *arrayTemp = [self.dictListFiltered objectForKey:strPriceListCategory];
  113. [arrayTemp addObject:dict];
  114. [self.dictListFiltered setObject:arrayTemp forKey:strPriceListCategory];
  115. } else {
  116. NSMutableArray *arrayTemp = [[NSMutableArray alloc] initWithObjects:dict, nil];
  117. [self.dictListFiltered setObject:arrayTemp forKey:strPriceListCategory];
  118. }
  119. } else {
  120. if ([[self.dictList allKeys] containsObject:strPriceListCategory]) {
  121. NSMutableArray *arrayTemp = [self.dictList objectForKey:strPriceListCategory];
  122. [arrayTemp addObject:dict];
  123. [self.dictList setObject:arrayTemp forKey:strPriceListCategory];
  124. } else {
  125. NSMutableArray *arrayTemp = [[NSMutableArray alloc] initWithObjects:dict, nil];
  126. [self.dictList setObject:arrayTemp forKey:strPriceListCategory];
  127. }
  128. }
  129.  
  130. }
  131. } else { //if search results yield no json array, then remove all objects from dictionary
  132. [self.dictList removeAllObjects];
  133. [self.dictListFiltered removeAllObjects];
  134. }
  135. [self.tablView reloadData];
  136. }
  137.  
  138. - (void)didReceiveMemoryWarning {
  139. [super didReceiveMemoryWarning];
  140. // Dispose of any resources that can be recreated.
  141. }
  142.  
  143. #pragma mark - TableView Datasource
  144.  
  145. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  146. NSArray *arrayTemp = [NSArray array];
  147. if (self.isFiltered) {
  148. NSArray *arrayListAllKeys = [self.dictListFiltered allKeys];
  149. arrayTemp = [self.dictListFiltered objectForKey:[arrayListAllKeys objectAtIndex:section]];
  150. } else {
  151. NSArray *arrayListAllKeys = [self.dictList allKeys];
  152. arrayTemp = [self.dictList objectForKey:[arrayListAllKeys objectAtIndex:section]];
  153. }
  154. return [arrayTemp count];
  155. }
  156.  
  157. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  158. SearchTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchTableCellId" forIndexPath:indexPath];
  159. NSDictionary *dict;
  160. if (self.isFiltered) {
  161. NSArray *arrayPriceListAllKeys = [self.dictListFiltered allKeys];
  162. NSArray *arrayPrice = [self.dictListFiltered objectForKey:[arrayPriceListAllKeys objectAtIndex:indexPath.section]];
  163. dict = [arrayPrice objectAtIndex:indexPath.row];
  164. } else {
  165. NSArray *arrayPriceListAllKeys = [self.dictList allKeys];
  166. NSArray *arrayPrice = [self.dictList objectForKey:[arrayPriceListAllKeys objectAtIndex:indexPath.section]];
  167. dict = [arrayPrice objectAtIndex:indexPath.row];
  168. }
  169. cell.lblBarCode.text = [[dict objectForKey:@"APNBARCODE"] objectForKey:@"text"];
  170. cell.lblPackDescription.text = [[dict objectForKey:@"PACKDESCRIPTION"] objectForKey:@"text"];
  171. cell.lblProduct.text = [[dict objectForKey:@"PRODUCT"] objectForKey:@"text"];
  172. cell.lblProductName.text = [[dict objectForKey:@"PRODUCTNAME"] objectForKey:@"text"];
  173.  
  174. return cell;
  175. }
  176.  
  177. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  178. if (self.isFiltered) {
  179. return [[self.dictListFiltered allKeys] count];
  180. } else {
  181. return [[self.dictList allKeys] count];
  182. }
  183. }
  184.  
  185. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  186. NSString *price = @"";
  187. if (self.isFiltered) {
  188. price = [[self.dictListFiltered allKeys] objectAtIndex:section];
  189. } else {
  190. price = [[self.dictList allKeys] objectAtIndex:section];
  191. }
  192. return price;
  193. }
  194.  
  195. - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  196. return 50.0;
  197. }
  198.  
  199. - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
  200. NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
  201. UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(8, 8, self.tablView.frame.size.width - 16, 30)];
  202. //If you add a bit to x and decrease y, it will be more in line with the tableView cell (that is in iPad and landscape)
  203. label.backgroundColor = [UIColor clearColor];
  204. label.textColor = [UIColor whiteColor];
  205. label.shadowColor = [UIColor whiteColor];
  206. label.shadowOffset = CGSizeMake(0.5, 0.5);
  207. label.font = [UIFont boldSystemFontOfSize:18];
  208. label.text = sectionTitle;
  209.  
  210. // Create header view and add label as a subview
  211. UIView *viewHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tablView.frame.size.width, 50)];
  212. viewHeader.backgroundColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1];
  213. [viewHeader addSubview:label];
  214. return viewHeader;
  215. }
  216.  
  217. #pragma mark - SearchBar Delegates
  218.  
  219. - (void)updateSearchResults
  220. {
  221. //You can use the below commented code in case you need an exact match of the PRODUCT value text you entered in search bar
  222. /*
  223. NSMutableArray *searchResults = [self.arrayList mutableCopy];
  224. NSString *strippedString = [searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  225. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"PRODUCT.text==[c] %@", strippedString];
  226. searchResults = [[searchResults filteredArrayUsingPredicate:predicate] mutableCopy];
  227. // hand over the filtered results to our search results table
  228. self.arrayFilteredList = searchResults;
  229. //NSLog(@"%@", self.arrayFilteredPriceList);
  230. [self groupXMLinSectionsWithArray:self.arrayFilteredList];
  231. */
  232.  
  233.  
  234. //Below code searches depending on Product / Product Name / APNBarCode values
  235. NSString *searchText = self.searchBr.text;
  236. NSMutableArray *searchResults = [self.arrayList mutableCopy];
  237. NSString *strippedString = [searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  238. NSArray *searchItems = nil;
  239. if (strippedString.length > 0) {
  240. searchItems = [strippedString componentsSeparatedByString:@" "];
  241. }
  242.  
  243. NSMutableArray *andMatchPredicates = [NSMutableArray array];
  244.  
  245. for (NSString *searchString in searchItems) {
  246. NSMutableArray *searchItemsPredicate = [NSMutableArray array];
  247.  
  248. // Below we use NSExpression represent expressions in our predicates.
  249. // NSPredicate is made up of smaller, atomic parts: two NSExpressions (a left-hand value and a right-hand value)
  250.  
  251. // Product
  252. NSExpression *lhsProduct = [NSExpression expressionForKeyPath:@"PRODUCT.text"];
  253. NSExpression *rhsProduct = [NSExpression expressionForConstantValue:searchString];
  254. NSPredicate *finalPredicateProduct = [NSComparisonPredicate
  255. predicateWithLeftExpression:lhsProduct
  256. rightExpression:rhsProduct
  257. modifier:NSDirectPredicateModifier
  258. type:NSContainsPredicateOperatorType
  259. options:NSCaseInsensitivePredicateOption];
  260. [searchItemsPredicate addObject:finalPredicateProduct];
  261.  
  262. // Product Name
  263. NSExpression *lhsProductName = [NSExpression expressionForKeyPath:@"PRODUCTNAME.text"];
  264. NSExpression *rhsProductName = [NSExpression expressionForConstantValue:searchString];
  265. NSPredicate *finalPredicateProductName = [NSComparisonPredicate
  266. predicateWithLeftExpression:lhsProductName
  267. rightExpression:rhsProductName
  268. modifier:NSDirectPredicateModifier
  269. type:NSContainsPredicateOperatorType
  270. options:NSCaseInsensitivePredicateOption];
  271. [searchItemsPredicate addObject:finalPredicateProductName];
  272.  
  273.  
  274. // APN Bar Code
  275. NSExpression *lhsAPNBarCode = [NSExpression expressionForKeyPath:@"APNBARCODE.text"];
  276. NSExpression *rhsAPNBarCode = [NSExpression expressionForConstantValue:searchString];
  277. NSPredicate *finalPredicateAPNBarCode= [NSComparisonPredicate
  278. predicateWithLeftExpression:lhsAPNBarCode
  279. rightExpression:rhsAPNBarCode
  280. modifier:NSDirectPredicateModifier
  281. type:NSContainsPredicateOperatorType
  282. options:NSCaseInsensitivePredicateOption];
  283. [searchItemsPredicate addObject:finalPredicateAPNBarCode];
  284.  
  285. // AVERAGECOST
  286. NSExpression *lhsPACKDESCRIPTION = [NSExpression expressionForKeyPath:@"PACKDESCRIPTION.text"];
  287. NSExpression *rhsPACKDESCRIPTION = [NSExpression expressionForConstantValue:searchString];
  288. NSPredicate *finalPredicatePACKDESCRIPTIONt = [NSComparisonPredicate
  289. predicateWithLeftExpression:lhsPACKDESCRIPTION
  290. rightExpression:rhsPACKDESCRIPTION
  291. modifier:NSDirectPredicateModifier
  292. type:NSContainsPredicateOperatorType
  293. options:NSCaseInsensitivePredicateOption];
  294. [searchItemsPredicate addObject:finalPredicatePACKDESCRIPTIONt];
  295.  
  296. // at this OR predicate to our master AND predicate
  297. NSCompoundPredicate *orMatchPredicates = [NSCompoundPredicate orPredicateWithSubpredicates:searchItemsPredicate];
  298. [andMatchPredicates addObject:orMatchPredicates];
  299.  
  300. }
  301.  
  302. // match up the fields of the Product object
  303. NSCompoundPredicate *finalCompoundPredicate =
  304. [NSCompoundPredicate andPredicateWithSubpredicates:andMatchPredicates];
  305. searchResults = [[searchResults filteredArrayUsingPredicate:finalCompoundPredicate] mutableCopy];
  306. // hand over the filtered results to our search results table
  307. self.arrayFilteredList = searchResults;
  308. //NSLog(@"%@", self.arrayFilteredPriceList);
  309.  
  310. [self groupXMLinSectionsWithArray:self.arrayFilteredList];
  311. }
  312.  
  313. //This method gets called when user starts entering text in search bar
  314. - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
  315. if (searchText.length == 0) {
  316. self.isFiltered = NO;
  317. [self.dictList removeAllObjects];
  318. [self groupXMLinSectionsWithArray:self.arrayList];
  319. [self.tablView reloadData];
  320. } else {
  321. self.isFiltered = YES;
  322. self.arrayFilteredList = [NSMutableArray new];
  323. [self.dictListFiltered removeAllObjects];
  324. [self updateSearchResults];
  325. }
  326. }
  327.  
  328. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
  329. [searchBar resignFirstResponder];
  330. [self.dictList removeAllObjects];
  331. [self groupXMLinSectionsWithArray:self.arrayList];
  332. [self.tablView reloadData];
  333. }
  334.  
  335. - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
  336. [searchBar resignFirstResponder];
  337. [self.tablView reloadData];
  338. }
  339.  
  340.  
  341. @end
  342.  
  343. [
  344. {
  345. "PRODUCT": {
  346. "text": "GELDCMFRAME"
  347. },
  348. "PRODUCTMAJORGROUP": {
  349. "text": "IC"
  350. },
  351. "PRICELISTCATEGORY": {
  352. "text": "GELDISP"
  353. },
  354. "APNBARCODE": {
  355. "text": "931000"
  356. },
  357. "PACKDESCRIPTION": {
  358. "text": "Some Description"
  359. },
  360. "PRODUCTNAME": {
  361. "text": "Description"
  362. }
  363. and so on
  364. }, and so on
  365. ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement