Correcting user submitted URL in Xcode/Objective C

天涯浪子 提交于 2019-12-13 08:58:31

问题


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:


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
}


来源:https://stackoverflow.com/questions/17349428/correcting-user-submitted-url-in-xcode-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!