42

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

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

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

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?

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165

6 Answers6

76

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)
Community
  • 1
  • 1
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
  • 13
    `let urlStr = url.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())` – Eugene Braginets Jan 09 '16 at 20:12
  • 2
    let urlStr = url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) – Alex Jun 07 '16 at 03:06
  • 2
    This fixed a problem that I began seeing with Swift 3. Not sure why my `urlStr` was able to get through in Swift 2.2, but adding `.addingPercentEncoding...` fixed it. – blwinters Aug 19 '16 at 17:37
  • One suggestion is to safely unwrap the url just in case it has garbage data or nil in it. Use "guard let" or "if let" syntax to do so. Check my answer below for more information – Matthew Zourelias Jun 07 '17 at 20:15
  • The above solution in ObjC `[url stringByAddingPercentEncodingWithAllowedCharacters:NSCharact‌​erSet.URLQueryAllowe‌​dCharacterSet];` – Rushabh Oct 24 '17 at 00:39
  • @Richie How can i covert this type of string into URL. File saved with Chinese character. /var/mobile/Containers/Data/Application/5F160C54-414A-4741-BDE5-4B5C0126F026/Documents/從出差錯.csv . I am opening URL with webview and it is working fine with english but not for other languages. – Mitesh Dobareeya Jan 26 '18 at 12:00
44

as blwinters said, in Swift 3.0 use

URL(string: urlPath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
djdance
  • 3,110
  • 27
  • 33
2

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!)")
Ilesh P
  • 3,940
  • 1
  • 24
  • 49
2

You can get following error if NSURL is null and trying load http URL over web view:

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

}
MobileGeek
  • 2,462
  • 1
  • 26
  • 46
2

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)
}
Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42
1

SWIFT 3.0

A safe way to fix a bad string being converted to NSURL is by unwrapping the urlPath string variable using "guard let"

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.

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. No logic as to why it was random even when I printed the url's they would look fine. As soon as I added the .addingPercentEncoding it was back working without any issues whatsoever.

tl;dr For anyone reading this, try my above code and swap out "urlPath" for your own local string url.