如何确定字符串是否是Objective-C中的URL [英] How to determine if a string is a URL in Objective-C

查看:59
本文介绍了如何确定字符串是否是Objective-C中的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是iPhone开发和Objective-C的新手.使用ZBar SDK,我开发了一个基本应用程序,可以扫描相册中的QR图像并输出其翻译结果.

我想知道是否有办法获取此输出,确定是否为URL,是否可以在Web浏览器中打开它.

如果传递的URL无效,则解决方案

NSURL的URLWithString返回nil.因此,您只需检查返回值即可确定URL是否有效.

更新

仅使用URLWithString:通常是不够的,您可能还想检查url是否具有方案和主机,否则,诸如al:/dsfhkgdsk的url将通过测试.

所以您可能想做这样的事情:

NSURL *url = [NSURL URLWithString:yourUrlString];
if (url && url.scheme && url.host)
{
   //the url looks ok, do something with it
   NSLog(@"%@ is a valid URL", yourUrlString);
}

如果您只想接受http URL,则可能要添加[url.scheme isEqualToString:@"http"].

I'm new to iPhone development and Objective-C. Using the ZBar SDK I've developed a basic app which scans a QR image from the photo album and outputs what it translates to.

I want to know if there is a way to take this output, determine whether it is a URL and if so open it in a web browser.

解决方案

NSURL's URLWithString returns nil if the URL passed is not valid. So, you can just check the return value to determine if the URL is valid.

UPDATE

Just using URLWithString: will usually not be enough, you probably also want to check if the url has a scheme and a host, otherwise, urls such as al:/dsfhkgdsk will pass the test.

So you probably want to do something like this:

NSURL *url = [NSURL URLWithString:yourUrlString];
if (url && url.scheme && url.host)
{
   //the url looks ok, do something with it
   NSLog(@"%@ is a valid URL", yourUrlString);
}

If you only want to accept http URLs you may want to add [url.scheme isEqualToString:@"http"].

这篇关于如何确定字符串是否是Objective-C中的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆