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

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

本文介绍了将String转换为NSURL在swift中返回nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串转换为 NSURL ,我的代码如下:

I am trying to convert a String to NSURL and my code for that is Below:

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)")

控制台打印的内容如下:

And console prints something like this:

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

remoteUrl nil 我不知道这里有什么问题。

The remoteUrl is nil and I don't know what is the problem here.

之后我尝试排序 String 像这样:

After that I try sort String like this:

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)

这个工作正常。

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

So can anybody please tell me what is wrong with my first case?

推荐答案

正如Martin R所说,我看到帖子,我将目标-c代码转换为swift,我得到了这个代码:

As suggested by the Martin R, I see THIS post and I converted that objective-c code to swift and I got this code:

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:

For 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)

这篇关于将String转换为NSURL在swift中返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 06:29