我正在使用UISearchBar处理iOS应用。我想为用户添加一个选项,以便使用可以在搜索栏中输入的轻量级搜索查询,例如邮件应用。
例如,我希望能够解析“上一个搜索字词:周”并搜索我的数据“搜索字词”并创建一个搜索过滤器,仅显示过去7天。 如何解析iOS String中的命令行参数?
特别是,一旦我提取了我的代币并确认它们是有效的, 如何从搜索查询中删除它们而不影响查询的其余部分?
这是我最初的尝试。我可以使用现成的工具来完成这项任务吗?
static NSString* whenKeyword = @"when";
static NSString* lastKeyword = @"last";
-(NSMutableDictionary*)findCommandsInQuery:(NSString*)query
{
//extract keywords from the query, like google mail search. We want to have commands like "cute puppies Last:month"
//remove extra whitespace, prepare to parse
NSString* dirtyString = [query stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSArray* tokens = [dirtyString componentsSeparatedByString:@":"];
//for each token, we want to trim it and remove illegal characters
NSMutableArray* cleanTokens = [[NSMutableArray alloc] initWithCapacity:tokens.count];
NSString* token = nil;
NSString* nextToken = nil;
NSString* cleanToken = nil;
for(int i = 0; i< tokens.count; i ++)
{
//get a token, for example "cute puppies last"
token = tokens[i];
NSArray* words = [token componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if(words.count >0)
{
for(NSString* word in words)
{
cleanToken = [DataSource cleanTrimSearchTerm:word];
if(cleanToken.length > 0)
{
[cleanTokens addObject:cleanToken];
}
}
}else
{
cleanToken = nil;
}
}
//process tokens
NSMutableDictionary* commands = [NSMutableDictionary dictionary];
for(int i = 0; i< cleanTokens.count; i ++)
{
token = cleanTokens[i];
if(i+1 < cleanTokens.count)
{
nextToken = cleanTokens[i+1];
}
[self checkToken:token againstKeyword:whenKeyword withQuantifier:nextToken storeInDictionary:commands];
[self checkToken:token againstKeyword:lastKeyword withQuantifier:nextToken storeInDictionary:commands];
}
DLog(@"found commands: %@",commands);
return commands;
}
这是一种响应命令并使用它们创建搜索查询的方法
-(void)processCommands:(NSMutableDictionary*)commands
{
NSString* value = commands[lastKeyword];
if(value != nil)
{
DLog(@"%@" ,value);
if([value isEqualToString:@"day"])
{
}else if ([value isEqualToString:@"week"])
{
}else if ([value isEqualToString:@"month"])
{
}else if ([value isEqualToString:@"quarter"])
{
}else if ([value isEqualToString:@"year"])
{
}
}
}
答案 0 :(得分:1)
用户通常不喜欢学习查询语言。这是一个复杂的用户体验。有许多不同的方法可以简化查询和搜索,例如使用UISearchController的范围栏或使用表视图部分来划分信息。但是,如果仍然需要创建查询机制,请尝试实现自己的抽象语法树(AST)以避免意大利面条代码