简体   繁体   English

将字符串转换为 NSURL 在 swift 中返回 nil

[英]Convert String to NSURL is return nil in swift

I am trying to convert a String to NSURL and my code for that is Below:我正在尝试将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)")

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

The remoteUrl is nil and I don't know what is the problem here. remoteUrl nil ,我不知道这里有什么问题。

After that I try sort String like this:之后,我尝试像这样对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)")

And console prints:和控制台打印:

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)

This is working fine.这工作正常。

So can anybody please tell me what is wrong with my first case?那么有人可以告诉我我的第一个案例有什么问题吗?

As suggested by the Martin R, I see THIS post and I converted that objective-c code to swift and I got this code:正如 Martin R 所建议的那样,我看到了这篇文章,我将目标 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)

and this is working correctly.这工作正常。

For swift 3.0:对于 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)

正如 blwinters 所说,在Swift 3.0 中使用

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

I think try this it's perfectly work for me我认为试试这个它对我来说非常有用

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

You can get following error if NSURL is null and trying load http URL over web view:如果 NSURL 为 null 并尝试通过 Web 视图加载 http URL,您可能会收到以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

To be safe we should use:为了安全起见,我们应该使用:

 var urlStr = strLink!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

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

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

}

this work for me这对我有用

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

SWIFT 3.0斯威夫特 3.0

A safe way to fix a bad string being converted to NSURL is by unwrapping the urlPath string variable using "guard let"修复转换为 NSURL 的错误字符串的安全方法是使用“guard let”解开 urlPath 字符串变量

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

The variable called "urlPath" in my above example would be the url string you have already declared somewhere else in your code.在我上面的示例中,名为“urlPath”的变量将是您已经在代码中的其他地方声明的 url 字符串。

I came across this answer because randomly I was getting the nil error with XCode breaking at the point my string was made into a NSURL.我遇到了这个答案,因为在我的字符串被转换为 NSURL 时,我随机收到了 XCode 中断的 nil 错误。 No logic as to why it was random even when I printed the url's they would look fine.没有逻辑为什么它是随机的,即使我打印了 url,它们看起来也不错。 As soon as I added the .addingPercentEncoding it was back working without any issues whatsoever.一旦我添加了 .addingPercentEncoding 它就可以正常工作了,没有任何问题。

tl;dr For anyone reading this, try my above code and swap out "urlPath" for your own local string url. tl; dr 对于阅读本文的任何人,请尝试我上面的代码并将“urlPath”替换为您自己的本地字符串 url。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM