在我正在开发的一个iPhone应用程序中,有一个可以输入网址的设置,由于表单和功能的原因,这个网址需要在线和离线验证。
到目前为止,我还没有找到任何方法来验证url,所以问题是;
如何在线和离线验证iPhone (Objective-C)上的URL输入?
发布于 2016-04-03 21:43:53
扩展@Anthony对swift的回答,我在String上写了一个类别,它返回一个可选的NSURL。如果无法验证String是否为URL,则返回值为nil。
import Foundation
// A private global detector variable which can be reused.
private let detector = try! NSDataDetector(types: NSTextCheckingType.Link.rawValue)
extension String {
func URL() -> NSURL? {
let textRange = NSMakeRange(0, self.characters.count)
guard let URLResult = detector.firstMatchInString(self, options: [], range: textRange) else {
return nil
}
// This checks that the whole string is the detected URL. In case
// you don't have such a requirement, you can remove this code
// and return the URL from URLResult.
guard NSEqualRanges(URLResult.range, textRange) else {
return nil
}
return NSURL(string: self)
}
}https://stackoverflow.com/questions/1471201
复制相似问题