Check if an URL has got http:// prefix

2019-03-18 04:07发布


In my application, when the user add an object, can also add a link for this object and then the link can be opened in a webView.
I tried to save a link without http:// prefix, then open it in the webView but that can't open it!
Before webView starts loading, is there a method to check if the URL saved has got http:// prefix? And if it hasn't got it, how can I add the prefix to the URL?
Thanks!

8条回答
Anthone
2楼-- · 2019-03-18 04:41
NSString * urlString = ...;
NSURL * url = [NSURL URLWithString:urlString];
if (![[url scheme] length])
{
  url = [NSURL URLWithString:[@"http://" stringByAppendingString:urlString]];
}
查看更多
在下西门庆
3楼-- · 2019-03-18 04:44

First, you should create a new category for NSURL: File > New File > Objective-C Category. You can call the category something along the lines of HTTPURLWithString, make it a category of NSURL, press next and add it to your target. Then in the NSURL+HTTPURLFromString.m implement the following message (and declare the message in your .h)

@implementation NSURL (HTTPURLFromString)
+(NSURL *)HTTPURLFromString:(NSString *)string
{
    NSString *searchString = @"http";
    NSRange prefixRange = [string rangeOfString:searchString options:(NSCaseInsensitiveSearch | NSAnchoredSearch)];

    if (prefixRange.length == 4) {
        return [NSURL URLWithString:string];
    }
    return [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", string]];

}
@end

To open a link in the WebView is simply

NSString *urlString = @"www.google.com";
NSURL *url = [NSURL HTTPURLFromString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView.mainFrame loadRequest:request];
查看更多
登录 后发表回答