Swift. Url Returning Nil

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.

Swift URL returns nil when the url contains an internationalized domain name (IDN)

Until, someone can find a way to tell the URL framework to correctly represent the URL "https://համընդհանուր-ընկալում-թեստ.հայ", it is possible to translate the domain part to an A-LABEL before passing it to the URL constructor and elude its wrong internal representation:

import Foundation
import IDNA

// an idn domain:
let uLabel = "համընդհանուր-ընկալում-թեստ.հայ"
guard let aLabel = uLabel.idnaEncoded else { exit(1) }
let supportedUrl = "https://" + aLabel
guard let url = URL(string: supportedUrl) else { exit(1) }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let rawContent = data else { exit(1) }
guard let content = String(data: rawContent, encoding: String.Encoding.utf8) else { exit(1) }
if content.contains("UASG Testbed Landing Page") {
// successfully fetch content of the page
exit(0)
} else {
// error during fetching
exit(1)
}
}
task.resume()
RunLoop.main.run()

This piece of code does exit 0. The IDNA library is there (ensure you take the master branch, because released versions are still on IDNA2003):

https://github.com/Wevah/IDNA-Cocoa

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

URL is always nil in Swift 3

You´re getting nil because the URL contains a space. You need to encode the string first and then convert it to an URL.

func getJSON(strURL: String)  {
if let encoded = strURL.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
let myURL = URL(string: encoded) {
print(myURL)
}

var dictReturn:Dictionary<String, Any> = [:]

//cancel data task if it is running
myDataTask?.cancel()
}

URL will be:

https://itunes.apple.com/search?media=music&entity=song&term=The%20Chain

URL with string tel://*#06# is returning nil in Swift

According to apple documentation here :

To prevent users from maliciously redirecting phone calls or changing the behavior of a phone or account, the Phone app supports most, but not all, of the special characters in the tel scheme. Specifically, if a URL contains the * or # characters, the Phone app does not attempt to dial the corresponding phone number.

Please note that for other characters, you can use addingPercentEncoding method to escape special characters which returns a properly escaped version of your original string.

Example:

let encoding = phoneNumberString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

URL(string:) returns nil for a path that contains cyrillic

You’ll need to URL encode the path:

https://somedomain.ru/upload/files/%D0%9E%D1%84%D0%B5%D1%80%D1%82%D0%B0.pdf

Apple docs: addingPercentEncoding(withAllowedCharacters:)

Why is url.bookmarkData returning nil?

Used a technical ticket for apple and they came with a solution :D

NSFileCoordinator().coordinate(readingItemAt: url, options: .withoutChanges, error:&err, byAccessor: { (newURL: URL) -> Void in
do {
let bookmark = try newURL.bookmarkData()
} catch let error {
print("\(error)")
}
})

if let err = err {
print(err.localizedDescription)
}


Related Topics



Leave a reply



Submit