Correcting user submitted URL in Xcode/Objective C

2019-09-21 02:24发布

I'm trying to programme a mini browser in Xcode however at the moment the UIWebView will only load URLs that include the http ://www The user submits their URL using a UITextField and the contents become a string.

I wondered if there was a way to either search the submitted string and add the http or www or both where required or format the text input so it automatically checks to see if the correct address is used.

Thanks

1条回答
Melony?
2楼-- · 2019-09-21 03:17

Do something like this:

NSString *urlString = ... // the user entered URL string
if (![urlString hasPrefix:@"http://"]) {
    urlString = [@"http://" stringByAppendingString:urlString];
}

Note that this is just a rough suggestion to get you started. This code doesn't handle cases such as the URL already having a prefix of "https://" or typos such as "htp://".

A better approach might be:

NSURL *url = [NSURL URLWithString:urlString];
NSString *scheme = [url scheme];
if (scheme.length == 0) {
    // The string has no scheme - add "http://"
} else {
    // check for valid schemes
}
查看更多
登录 后发表回答