Convert String to Nsurl Is Return Nil in Swift

Convert String to NSURL is return nil in 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)

and this is working correctly.

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)

Convert String to URL (Why is resulting variable nil)

You've found a bug in the debugger!

[This bug is slated to be fixed in Xcode 12.5.]

It's easy to reproduce it:

Sample Image

We have paused at a breakpoint inside the condition. So obviously url is not nil or we wouldn't be here at all.

Another way to prove this is to po url in the console (see right-bottom of this screen shot):

Sample Image

Nevertheless, url shows as nil both in the tooltip and in the variables list. So the debugger is just lying to you: url is not nil. Don't worry, be happy. Your code is working fine.

EDIT The bug has something to do with the Swift Foundation overlay. If you change the declaration of url to this:

let url = NSURL(string: urlAsString)

...then everything works as expected.

And see also https://stackoverflow.com/a/58156592/341994

Conversion From String to NSURL constantly returns nil

You need to use the filePath specific initialiser

let audioPathURL: NSURL? = NSURL(fileURLWithPath: audioPath)

Casting String to NSURL returns nil

The problem is the vertical bars (|) in the query part of your URL. They should be escaped as %7C.

Here's how I would construct the URL which auto-escape the query part:

var components = NSURLComponents(string: "https://maps.googleapis.com/maps/api/staticmap")!
components.query = "key=AIzaSyAJeHxZaZuNsYimNCJ4r0yuO-OYM8cINOI¢er=6.241381,-75.595083&zoom=13&size=600x300&path=color:0x0000ff|weight:5|6.241381,-75.595083&signature=u7sM3m2h-qFSJoARR7cqD0CSBvU="

if let url = components.url {
// ...
}

If you are using Swift 3, NSURLComponents is renamed to URLComponents

Swift. URL returning nil

Don't force unwrap it with (!). When you use (!) and the value of the variable is nil, your program crashes and you get that error. Instead, you want to safely unwrap the optional with either a "guard let" or an "if let" statement.

guard let name = element.Name as? String else {
print("something went wrong, element.Name can not be cast to String")
return
}

if let url = URL(string: "http://en.wikipedia.org/wiki/\(name)") {
UIApplication.shared.openURL(url)
} else {
print("could not open url, it was nil")
}

If that doesn't do the trick, you may have an issue with element.Name. So I would check to see if that's an optional next if you're still having issues.

Update

I added a possible way to check the element.Name property to see if you can cast it as a String and create the desired url you're looking to create. You can see the code above the code I previously posted.

NSURL returns nil

Your updated output explains your issue. There is a newline character at the end of urlString. You need to cleanup the string from wherever you are obtaining those URLs.

let cleanURL = badURL.trimmingCharacters(in: . whitespacesAndNewlines)

NSURL is returning nil for a valid URL

It should work: Here is why http://www.url-encode-decode.com

        let url = NSURL(string: urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)

Since above API is deprecated alternative approach is

    let url = NSURL(string: urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)


Related Topics



Leave a reply



Submit