【问题标题】:Maniupulating URLs -- Best way操纵 URL——最好的方法
【发布时间】:2011-07-22 17:27:08
【问题描述】:
【问题讨论】:
标签:
iphone
cocoa-touch
nsurl
【解决方案1】:
如果你使用的是 iOS7,你可以使用 NSURLComponents,看这个例子:
NSString *urlString = @"https://mail.google.com/mail/u/0";
NSURLComponents *components = [[NSURLComponents alloc] initWithString:urlString];
[components setQuery:@"shva=1"];
其他例子:
//Example One
NSString *urlString = @"https://mail.google.com/mail/u/0/?shva=1#inbox";
NSURLComponents *components = [[NSURLComponents alloc] initWithString:urlString];
NSLog(@"%@ - %@ - %@ - %@", components.scheme, components.host, components.query, components.fragment);
//Example Two
NSString *urlString = @"https://mail.google.com/mail/u/0/?shva=1#inbox";
NSURLComponents *components = [[NSURLComponents alloc] initWithString:urlString];
if (components) {
//good URL
} else {
//bad URL
}
//Example three
NSURLComponents *components = [NSURLComponents new];
[components setScheme:@"https"];
[components setHost:@"mail.google.com"];
[components setQuery:@"shva=1"];
[components setFragment:@"inbox"];
[components setPath:@"/mail/u/0/"];
[self.webview loadRequest:[[NSURLRequest alloc] initWithURL:[components URL]]];
但是使用 NSURLComponents 你可以做很多其他事情,检查 NSURLComponents 的公共接口,官方文档还没有在线可用。
【解决方案2】:
如果您需要替换 get 参数,您可以将该 URL 字符串存储到可变字符串中,然后使用 rangeOfString 查找 &yourvar= 或 ?yourvar= 模式,然后确定该变量值的结束位置并替换它价值。
或者,我可能会使用
comps = [URLstring componentsSeparatedByString:@"?"],
然后getParams = [NSMutableArray arrayWithArray:[[comps objectAtIndex:1] componentsSeparatedByString:@"&"]]
最后遍历 getParams 和 var = [NSMutableArray arrayWithArray:[[getParams objectAtIndex:counter] componentsSeparatedByString:@"="]]。
第一步在 URI 和 GET 参数之间进行拆分。第二步拆分 GET 参数。第三步使您可以访问每个参数名称及其值。如果它们与您的搜索匹配,您可以在此步骤修改要修改的变量。
当您结束每个处理步骤时,您必须使用 [var componentsJoinedByString:@"&"] 为每个处理步骤保存结果。
【解决方案3】:
如果你的网址是固定的,那么你问这个问题就很简单了。
NSString * string = [NSString stringWithFormat: ...];
方法会有所帮助。但在我看来,您的网址也不是固定的。这就是您发布问题的原因。
您可以尝试获取“=”和“&”字符的索引。然后,您可以使用 NSString 类对象方法来获取子字符串,您可以将其替换为您的值,这将再次是字符串。
或者您可以将字符串转换为 const char *,然后尝试对其进行操作。