URL keeps returning nil [duplicate] - swift

I'm trying to create an URL variable from a string value. I don't understand why the resulting URL is nil
I have set up a new Xcode macOS project, placed a simple button on the View, created an action for that button and implemented the following code. The resulting url is nil.
I tried the same in Swift playground and there it worked...
#IBAction func buttonClicked(_ sender: Any) {
let urlAsString = "http://www.google.de/"
let url = URL(string: urlAsString)
if url != nil {
// Do work...
}
}
urlAsString is "http://www.google.de/" but
url is nil
debugger

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

Related

Trigger a segue from a function (without UI element)

I'm very new with programming. Currently, I need to trigger a segue directly after a function is being executed.
This is my code:
func onlineSearch() {
let urlToGoogle = "https://www.google.com/search?q=\(resultingText)"
let urlString = urlToGoogle.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
url = URL(string: urlString!)
performSegue(withIdentifier: K.goToBrowser, sender: nil)
}
}
When I run this, I get this error:
Warning: Attempt to present <MyApp.SFSafariViewController: 0x10153be70> on <MyApp.CameraViewController: 0x101708460> whose view is not in the window hierarchy!
But if I run all the same, but simply trigger the segue from a button, instead of the way I want, it actually works perfectly.
#IBAction func webViewButtonPressed(_ sender: UIButton) { // TEMP
performSegue(withIdentifier: K.goToBrowser, sender: self)
}
P.S.: Nevermind the grotesque unwrapping, it is just working as a placeholder right now.
Reposting my comment as an answer with a code snippet -
If the caller of onlinesearch() may be on anything other than the main thread, you need to wrap the performSegue call in a DispatchQueue.main.async{} block.
DispatchQueue.main.async {
performSegue(withIdentifier: K.goToBrowser, sender: nil)
}
Generally, methods which affect UI (updating controls, performing segues, etc.) need to be on the main thread. Calls from UIKit are already on the main thread (viewDidLoad, draw, events, notifications, timers etc.), but other task completion handlers (and anything run on explicitly on a different queue) may not be.
try using this to open the safari URL
if let url = URL(string: "https://www.google.com/search?q=\(resultingText)") {
UIApplication.shared.open(url)
}
Here's a function if you want to use it anywhere else.
But you should mark Chris Comas answer as the correct one.
func openURL(url: URL) {
UIApplication.shared.open(url, options: [:])
}
}
Just for the sake of knowledge:
let urlGoogle = URL(string: "https://www.google.com")
openURL(url: urlGoogle)
if you want to open the browser inside the app check Swift documentation: https://developer.apple.com/documentation/uikit/uiwebview

Convert String to URL (Why is resulting variable nil)

I'm trying to create an URL variable from a string value. I don't understand why the resulting URL is nil
I have set up a new Xcode macOS project, placed a simple button on the View, created an action for that button and implemented the following code. The resulting url is nil.
I tried the same in Swift playground and there it worked...
#IBAction func buttonClicked(_ sender: Any) {
let urlAsString = "http://www.google.de/"
let url = URL(string: urlAsString)
if url != nil {
// Do work...
}
}
urlAsString is "http://www.google.de/" but
url is nil
debugger
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:
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):
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

Swift 4 - set value to webKit using evaluateJavaScript

I am trying to set a value from my project in Swift to a website using evaluateJavaScript but when I set the value he set success but he only placeholder not Really Value. How can I fix it?
See this image to understand what I mean:
#objc func handleStart() {
webView.evaluateJavaScript("document.getElementsByName('username')[0].value='\(textTagOne.text!)'", completionHandler: nil)
}
//This is HTML //

CGImage/ImageIO Code works in playground but not in OSX app

This routine returns nil in OSX 10.13.2 Beta but not in a playground. Don't have an older OS to test with at the moment.
func getImage(_ url: CFURL) -> CGImage? {
let sourceOptions = [
kCGImageSourceShouldAllowFloat as String: kCFBooleanTrue as NSNumber
] as CFDictionary
guard let imageSource = CGImageSourceCreateWithURL(url, sourceOptions) else { return nil }
guard let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) else {
let imageSourceStatus = CGImageSourceGetStatus(imageSource)
Swift.print("image nil, Image Source Status = \(imageSourceStatus)")
return nil
}
return image
}
imageSource is non-nil, but image is nil. The console message is "Image Source Status = CGImageSourceStatus", which is not one of the valid enum values.
Tried with both Swift 3.2 and Swift 4.0. The Dictionary arg in CGImageSourceCreateWithURL can be set to nil; nothing changes.
The correct frameworks are in the project (although it linked without them, so I'm not sure they matter.) Did "import ImageIO" but it built without it, so again I'm not sure in matters.
The URL is absolutely a valid file URL -- like I said, this works in the playground, and I've tried a number of different files and file types (tiff, jpg and png).
Any ideas?

instantiateViewControllerWithIdentifier is crashing (found nil)

When I try to instantiateViewControllerWithIdentifier on an iPhone it is crashing the app, although this works fine on the ios simulator. The code I have used is:
let questionsGameVC: QuestionsGame = self.storyboard?.instantiateViewControllerWithIdentifier("Questions") as! QuestionsGame
The error it is saying is
fatal error: unexpectedly found nil while unwrapping an Optional value
Can someone add anything to what is going wrong?
There are lots of places this could go wrong. I would put a breakpoint at that line and look at the state of the system, but debugging swift is still not in a great state. One alternative is to break apart that line of code and test all the pieces. Something like this:
if let storyboard = self.storyboard {
if let viewController = storyboard.instantiateViewControllerWithIdentifier("Questions") {
if let questionGame = viewController as? QuestionGame {
println("Success!")
} else {
println("Question game is the wrong type in the storyboard")
}
} else {
println("There is no view controller with the identifier Questions")
}
} else {
println("The storyboard is nil")
}
Whatever gets printed at the end should give you a better idea of where the problem is. Most often I have seen misspelled identifiers or situations where the class of the view controller in the storyboard has not been changed from UIViewController to the custom type.