将String转换为NSURL在swift中返回nil

时间:2015-02-14 10:23:41

标签: ios string swift nsurl

我正在尝试将String转换为NSURL,我的代码是:

var url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitude),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US"
    println("This is String: \(url)")
    var remoteUrl : NSURL? = NSURL(string: url)
    println("This is URL: \(remoteUrl)")

控制台打印出类似这样的内容:

This is String: https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997|-34.4356434,150.8858692|-34.4250728,150.89314939999997|-34.4356434,150.8858692|-34.4250728,150.89314939999997|-34.4356434,150.8858692|-34.423234,150.88658899999996|-34.423234,150.88658899999996|-34.428251,150.899673|-34.4257439,150.89870229999997|-34.423234,150.88658899999996|-34.4257439,150.89870229999997|-34.425376,150.89388299999996&language=en-US

This is URL: nil

remoteUrlnil,我不知道这里有什么问题。

之后我尝试像这样排序String

var url : String = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997&language=en-US"
    println("This is String: \(url)")
    var remoteUrl : NSURL? = NSURL(string: url)
    println("This is URL: \(remoteUrl)")

控制台打印:

This is String: https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997&language=en-US
This is URL: Optional(https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997&language=en-US)

这很好。

所以有人可以告诉我我的第一个案子有什么问题吗?

6 个答案:

答案 0 :(得分:71)

根据Martin R的建议,我看到THIS帖子,我将该Objective-c代码转换为swift,我得到了这段代码:

var url : NSString = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitud‌​e),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US" 
var urlStr : NSString = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! 
var searchURL : NSURL = NSURL(string: urlStr)! 
println(searchURL)

这是正常的。

对于swift 3.0:

let url : NSString = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitud‌​e),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US"
let urlStr : NSString = url.addingPercentEscapes(using: String.Encoding.utf8.rawValue)! as NSString
let searchURL : NSURL = NSURL(string: urlStr as String)!
print(searchURL)

答案 1 :(得分:37)

正如blwinters所说, Swift 3.0 使用

URL(string: urlPath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)

答案 2 :(得分:1)

我认为尝试这对我来说非常有用

  var url : String = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997&language=en-US"
        println("This is String: \(url)")
        var urlStr : NSString = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
        var remoteUrl : NSURL? = NSURL(string: url)
        println("This is URL: \(remoteUrl!)")

答案 3 :(得分:1)

如果NSURL为null并尝试在Web视图上加载http URL,则会出现以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

为了安全起见,我们应该使用:

 var urlStr = strLink!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

if var url = NSURL(string: urlStr!){
    println(self.strLink!)

    self.webView!.loadRequest(NSURLRequest(URL: url))

}

答案 4 :(得分:0)

SWIFT 3.0

修复转换为NSURL的错误字符串的一种安全方法是使用“guard let”展开urlPath字符串变量

guard let url = NSURL(string: urlPath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
            else
            {
                print("Couldn't parse myURL = \(urlPath)")
                return
            }

上面示例中名为“urlPath”的变量将是您已在代码中的其他位置声明的url字符串。

我遇到了这个答案,因为我随机地得到了一个nil错误,XCode在我的字符串变为NSURL的时候突破了。没有逻辑,为什么它是随机的,即使我打印网址,他们会看起来很好。一旦我添加了.addingPercentEncoding,它就会恢复正常运行而没有任何问题。

tl; dr对于阅读此内容的任何人,请尝试上面的代码并将“urlPath”替换为您自己的本地字符串网址。

答案 5 :(得分:0)

这项工作对我来说

let url : NSString = MyUrls.baseUrl + self.url_file_open as NSString
let urlStr : NSString = url.addingPercentEscapes(using: String.Encoding.utf8.rawValue)! as NSString
if let url = URL(string: urlStr as String) {
    let request = URLRequest(url: url)
    self.businessPlanView.loadRequest(request)
}