xcode 如何确定字符串是否是 Objective-C 中的 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3811996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:47:40  来源:igfitidea点击:

How to determine if a string is a URL in Objective-C

iphoneobjective-cxcode

提问by Zachary Markham

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.

我是 iPhone 开发和 Objective-C 的新手。使用 ZBar SDK 我开发了一个基本的应用程序,它扫描相册中的 QR 图像并输出它转换成的内容。

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.

我想知道是否有办法获取此输出,确定它是否是 URL,如果是,则在 Web 浏览器中打开它。

回答by Daniel

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.

如果传递的 URL 无效,NSURL 的 URLWithString 将返回 nil。因此,您只需检查返回值即可确定 URL 是否有效。

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:/dsfhkgdskwill pass the test.

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

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"].

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

回答by Rizwan Ahmed

Here is an alternative solution which I came across. You can do like this.

这是我遇到的一个替代解决方案。你可以这样做。

NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"yourstring"]];
bool valid = [NSURLConnection canHandleRequest:req];

Source : https://stackoverflow.com/a/13650542/2513947

来源:https: //stackoverflow.com/a/13650542/2513947

回答by Yash

You can look at below code to check whether a string contains website url or simple text.

您可以查看以下代码以检查字符串是否包含网站 url 或简单文本。

 NSString *getString =[[NSUserDefaults standardUserDefaults]valueForKey:@"searchKey"];
    if([getString rangeOfString:@"Www"].location == NSNotFound
       && [getString rangeOfString:@"www"].location == NSNotFound && [getString rangeOfString:@"com"].location == NSNotFound)
    {
        [companyNameTF setText:[[NSUserDefaults standardUserDefaults]valueForKey:@"searchKey"]];
    }
    else
    {
         [websiteTF setText:[[NSUserDefaults standardUserDefaults]valueForKey:@"searchKey"]];
    }