Objective-C 中的 URL 减去查询字符串
在 Objective-C 中获取 url 减去其查询字符串的最佳方法是什么?一个例子:
输入:
http://www.example.com/folder/page.htm?param1=value1¶m2=value2
输出:
http://www.example.com/folder/page.htm
是否有一个我缺少的 NSURL
方法来执行此操作?
What's the best way to get an url minus its query string in Objective-C? An example:
Input:
http://www.example.com/folder/page.htm?param1=value1¶m2=value2
Output:
http://www.example.com/folder/page.htm
Is there a NSURL
method to do this that I'm missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
从 iOS 8/OS X 10.9 开始,有一种更简单的方法可以使用 NSURLComponents 来完成此操作。
Since iOS 8/OS X 10.9, there is an easier way to do this with NSURLComponents.
我看不到 NSURL 方法。您可以尝试以下操作:
测试看起来不错:
运行此命令会产生:
There's no NSURL method I can see. You might try something like:
Testing looks good:
Running this produces:
这是 Andree 的答案 的 Swift 版本,带有一些额外的风味 -
你可以这样称呼它 -
Here is the Swift version of Andree's answer, with some extra flavour -
You can call it like -
Swift 版本
希望这有帮助!
Swift Version
Hope this helps!
您可能需要的是 url 的主机和路径组件的组合:
What you probably need is a combination of url's host and path components:
您可以尝试使用
NSURL
的query
来获取参数,然后使用NSString
的stringByReplacingOccurrencesOfString
删除该值?请注意,最终 URL 仍将以 ? 结尾,但如果需要,您也可以轻松删除它。
You could try using
query
ofNSURL
to get the parameters, then strip that value usingstringByReplacingOccurrencesOfString
ofNSString
?Note, the final URL will still end with ?, but you could easily strip that as well if needed.
我认为
-baseURL
可能会做你想要的。如果没有,您可以通过
NSString
进行往返,如下所示:I think
-baseURL
might do what you want.If not, you can can do a round trip through
NSString
like so:NSURL
有一个query
属性,其中包含 GET url 中?
之后的所有内容。因此,只需从absoluteString 的末尾减去它,您就得到了没有查询的url。日志:
+1
用于?
,它不是查询
的一部分。NSURL
has aquery
property which contains everything after the?
in a GET url. So simply subtract that from the end of the absoluteString, and you've got the url without the query.Logs:
The
+1
is for the?
which is not part ofquery
.您可能会喜欢
NSMutableString
类的replaceOccurrencesOfString:withString:options:range:
方法。我通过编写 类别 forNSURL
:这样,我可以将此消息发送到现有的
NSURL
对象,并让一个新的NSURL
对象返回给我。我使用以下代码对其进行了测试:
我得到了以下输出(减去时间戳):
请注意,问号(“?”)仍然存在。我将把它留给读者以安全的方式删除它。
You might fancy the method
replaceOccurrencesOfString:withString:options:range:
of theNSMutableString
class. I solved this by writing a category forNSURL
:This way, I can send this message to existing
NSURL
objects and have a newNSURL
object be returned to me.I tested it using this code:
and I got the following output (minus the time stamps):
Note that the question mark ('?') still remains. I will leave it up to the reader to remove it in a secure way.
我们应该尝试使用 NSURLComponents
We should try to use NSURLComponents
我认为您正在寻找的是
baseUrl
。I think what you're looking for is
baseUrl
.