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
Unwrapped URLRequest is always nil
In your code you are force-unwrapping (!
) every other optional
unnecessarily which is highly Not Recommended. Over-using the force-unwrapping is not a good coding practise. It may result into unexpected crashes in your app.
You must use optional binding (if-let
) and optional chaining for gracefully handling the optionals
.
if let requestURL = URL(string: autoLinkUrl) {
let request = URLRequest(url: requestURL)
if let vc = self.websiteRecordingVC {
vc.webView.load(request)
navigationController?.pushViewController(vc, animated: true)
}
}
Also, in your websiteRecordingVC
check if all the IBOutlets
are connected properly.
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.
URL to local Bundle.main always returns nil
If you add your video files to your main bundle, by dragging and drop it and copy items if needed, you can access them directly like this:
let url = Bundle.main.url(forResource: "Test" , withExtension: "mov")
If you want to access your video directly from the Asset, you can get it as NSObject
with NSDataAsset
.
let dataVideo : NSObject = NSDataAsset(name: "MyVideo")!
Edit:
If you add your Video/ Images to your MainBundle, you can see them when showing package content of your app. That's where the URL is pointing to. With asset you do not get a URL by stock. What I am doing is, I get the content of the Asset as Data, copy that into the Documents folder of my application and store it there. Then you get a URL to that directory aswell. (This should be the optimal solution for your case, I would just copy the videos to your Bundle directly)
URL.init?(string: String) returns 'nil' when it shouldn't
It would appear to be a REPL issue and existed in 11.0, too. But if you print(testUrl1)
, you’ll see it really is set.
URL(string:) gives nil error even if the String is not nil in Swift
The string is not nil
but it does not represent a valid URL. You have to encode the URL.
However it's recommended to unwrap the optionals safely
if let encodedString = codeString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let aURL = URL(string: encodedString), UIApplication.shared.canOpenURL(aURL) {
UIApplication.shared.openURL(aURL)
}
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:)
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
How to Remove an Element of a Given Value from an Array in Swift
Appearance Proxies/Ui_Appearance_Selector in Swift
How to Refactor Swift in Xcode
Sktextureatlas No Longer Sharing Textures in iOS 10
Wrapping a Generic Method in a Class Extension
Add Skreferencenode/Skscene to Another Skscene in Spritekit
How to Use Println in Swift to Format Number
How to Destroy a Singleton in Swift
Convert Date to Integer in Swift
In Swift, How to Write a Generic Function to Resize an Array
Dynamic/Runtime Dispatch in Swift, or "The Strange Way Structs Behave in One Man's Opinion"
Swift 4: Nsfilenamespboardtype Not Available. What to Use Instead for Registerfordraggedtypes
How to Compare Just the Time of a Date in Swift
How to Tell Which Guard Statement Failed
How to Load My Own Reality Composer Scene into Realitykit
How to Request a Desktop Version of a Webpage Using Uiwebview in Swift 3.0