-1

我正在尝试在 Xcode 中编写一个迷你浏览器,但是目前 UIWebView 只会加载包含 http://www 的 URL 用户使用 UITextField 提交他们的 URL,内容变为字符串。

我想知道是否有一种方法可以搜索提交的字符串并在需要的地方添加 http 或 www 或两者,或者格式化文本输入,以便它自动检查是否使用了正确的地址。

谢谢

4

1 回答 1

2

做这样的事情:

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

请注意,这只是一个粗略的建议,可以帮助您入门。此代码不处理 URL 已经具有前缀“https://”或拼写错误(例如“htp://”)等情况。

更好的方法可能是:

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
}
于 2013-06-27T17:28:14.990 回答