【发布时间】:2014-07-24 20:52:22
【问题描述】:
我这里有这个动作:
- (IBAction)searchButton:(id)sender {
NSString *textString = self.symbolSearchField.text;
NSURL *sourceURL = [[NSURL alloc] initWithString: [NSString stringWithFormat:@"http://query.yahooapis.com/v1/public/yql?q=select%%20*%%20from%%20yahoo.finance.quotes%%20where%%20symbol%%20in%%20%%28%%22%@%%22%%29&env=store://datatables.org/alltableswithkeys", textString]];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:sourceURL];
parser.delegate = self;
[parser parse];
我希望它从搜索字段中获取文本,使用该文本修改 URL,然后从 URL 解析 XML。但是,当我转义 *s 和 %s 时,URL 似乎会“损坏”,并且无法解析。如果我将 URL 保留原样而不转义...
NSURL *sourceURL = [[NSURL alloc] initWithString: [NSString stringWithFormat:@"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20%28%22%@%22%29&env=store://datatables.org/alltableswithkeys", textString]];
...然后我收到“无效的转换说明符 '*'”和“比数据参数更多的 '%' 转换”警告。
所以我的问题是,如何在不破坏 URL 的情况下转义符号?
编辑
为了清楚起见,这是我在进行一些调整后的代码。
NSString *textString = self.symbolSearchField.text;
NSString *query = [NSString stringWithFormat:@"select * from yahoo.finance.quotes where symbol in (\"%@\")", textString];
NSString *escapedStoreURL = [@"store://datatables.org/alltableswithkeys" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSString *escapedQuery = [query stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSString *URLString = [NSString stringWithFormat:@"http://query.yahooapis.com/v1/public/yql?q=%@&env=%@", escapedQuery, escapedStoreURL];
NSURL *sourceURL = [NSURL URLWithString:URLString];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:sourceURL];
parser.delegate = self;
[parser parse];
【问题讨论】:
标签: ios objective-c string parsing escaping