"Unexpectedly found nil" but the value is successfully checked with "print". Swift - ios

Getting an "unexpected found nil" error, but when checking the value - its there:
override func viewDidLoad() {
super.viewDidLoad()
if whichLink == "official link" {
let urlStr = videoGame.offLink!
let url = NSURL(string: urlStr)!
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
}
else if whichLink == "moby game link" {
print("yo yo yo, value is here! \(videoGame.mgLink) ")
let urlStr1 = videoGame.mgLink!
let url1 = NSURL(string: urlStr1)!
let request = NSURLRequest(URL: url1)
webView.loadRequest(request)
}
}
I'm suspecting an error in storyboard... but can't locate anything.
Did anyone has a clue what can be wrong?
The full project can be found # https://github.com/flostik2008/Favorite-Games

Your URL string is incorrectly formatted with the space at the end, so the NSURL initialization is returning nil.
You should URL encode all raw strings before trying to create an NSURL:
let urlStr1 = videoGame.mgLink!.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! should work

Related

How to convert String URL in Swift 5?

Im having a big trouble with URl
I want to use url for almofire , but unforutnately it always return nil
or ortherwise , this solutuin return valid URL but with weird $$*%&$( in front of https:// an resulting to always got nil response
let req = "​https://api-staging.xx.oo/v1/s-locations/"
guard let percentReq = req.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed ) else { return nil }
let urlReq = URL(string: percentReq)!
// work , url got , but fetch nothing
let urlReq = URL(string: req)!
// error FATAL
Honestly, looks like you managed to get some trash into the string by copy-pasting, I'm assuming it's encoding or something. This code from below works just fine:
let test = "https://api-staging.xx.oo/v1/s-locations/"
let url = URL(string: test)

Why does web view crashes

I'm calling a webpage in WKWebView but it always crashes when I launch the app, with this error message:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an
Optional value.
My code is below
let param = "https://myapp.mydomain.com/GameAPI/index.jsp?user=0202020767|0202020767"
let url = URL(string: param)
webView.load(URLRequest(url: url!))
At this point the nil is pointing to this code:
webView.load(URLRequest(url: url!))
I suspect that "|" character in the parameter is messing up your URL.
Try doing this:
let param = "user=0202020767|0202020767"
let escapedParam = param.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let fullURLString = "https://myapp.mydomain.com/GameAPI/index.jsp?\(escapedParam)"
if let url = URL(string: fullURLString) {
webView.load(URLRequest(url: url))
} else {
Swift.print("url is nil for some reason")
}
This is happening, because the url that you have tried to reach could not be resolved.
Also, you better use optional binding rather than forcing unwrap.
Here the code that you can check with valid url:
if let url = URL(string: "your url") {
webView.load(URLRequest(url: url))
} else {
print("could not open url, it is nil")
}

let url = URL(string: item)! returning nil in swift

Really cannot figure this one out, the URL prints and is not equal to nil, and it works in the browser when I paste it in. Any ideas?
import UIKit
class WebViewController: UIViewController {
var postLink: String = String()
#IBOutlet weak var mywebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
print(postLink)
let attempt = postLink
let url: URL = URL(string: attempt)!
let request: URLRequest = URLRequest(url: url)
mywebView.loadRequest(request)
}
The error occurs at:
let url: URL = URL(string: attempt)!
I am guess you are passing the urlString from another controller, do that instead
var postUrlString:String? //<-- make it optional
override func viewDidLoad() {
super.viewDidLoad()
guard let urlString = postUrlString, // forced unwrapped
let url = URL(string: urlString)
else { return } // if there is any optional we return
// else continue
let request: URLRequest = URLRequest(url: url)
mywebView.loadRequest(request)
}
The error is simple, postLink, you are providing to create URL is not correct. My guess is its empty.(Just a guess) and you have forgot to set it.
Avoid using force unwrapping ! in your code as much as possible.
You should either use guard let or if let in the scenarios.
In your case you might want to show some error to user when you are unable to load. Instead of
let url: URL = URL(string: attempt)!
use
if let url = URL(string: attempt) {
let request = URLRequest(url: url)
mywebView.loadRequest(request)
} else {
// Do something like. Show an alert that could not load webpage etc.
}
Alternatively you can use guard let, but it would require to return from the function where it is used. To know more about uses of if and guard let you can go through by blog post here.

How to purposely create a malformed URL in Swift

I have the following Swift extension on NSURL
public extension NSURL {
func getQueryItemValueForKey(key: String) -> String? {
guard let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false) else {
return nil
}
guard let queryItems = components.queryItems else { return nil }
return queryItems.filter {
$0.name == key
}.first?.value
}
}
I am writing unit tests for it but I am unable to get 100% code coverage as I don't seem to be able to get NSURLComponents(URL: self, resolvingAgainstBaseURL: false) to return nil. From what I understand, this requires a malformed URL but I am struggling to create one.
I have tried:
let url = NSURL(string: "")
let url = NSURL(string: "http://www.example")
let url = NSURL(string: "http://www.exam ple.com")
let url = NSURL(string: "http://www.example.com/?param1=äëīòú")
And some others that I lost track of. I know this is probably something blatantly obvious but i'm lost at the moment. So, how do I create a malformed URL in Swift?
As found in my research, you can produce a url that is malformed for NSURLComponents but not for NSURL by using negative port number (probably there are more cases but not sure):
let example = "http://example.com:-80/"
let url = NSURL(string: example)
print("url:\(url)") //prints out url:Optional(http://example.com:-80/)
if let url = url {
let comps = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)
print("comps:\(comps)") //prints out comps:nil
}

Swift / UIWebView with xpath / css

I have an element of a website that I want to display within a UIWebView. The element has a unique ID for css as well as for xpath. Is it possible? How would I be able to do that? Help is very appreciated.
I usualy use this code:
let url : NSURL! = NSURL(string: "http://blablablabla.com")
webView.loadRequest(NSURLRequest(URL: url))
But I don't want to display the whole page. Only the element with that ID.
I assume you are using UIWebView, not the newer WKWebView. What you need is an HTML parser (I chose HTMLReader). After downloading the page content, extract the div you want and replace the page's body with the innerHTML of that div.
The code below gets the Did you know section on Wikipedia:
import HTMLReader
override func viewDidLoad() {
super.viewDidLoad()
loadHTML()
}
func loadHTML() {
let url = NSURL(string: "https://en.wikipedia.org/wiki/Main_Page")!
let request = NSURLRequest(URL: url)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request) { data, response, error in
guard error == nil else {
print(error!.localizedDescription)
return
}
guard let data = data else {
print("data is nil")
return
}
let html = HTMLDocument(data: data, contentTypeHeader: nil)
if let head = html.firstNodeMatchingSelector("head"),
didYouKnow = html.firstNodeMatchingSelector("#mp-dyk") {
let newHTML = "<html><head>\(head.innerHTML)</head><body>\(didYouKnow.innerHTML)</body></html>"
self.webView.loadHTMLString(newHTML, baseURL: url)
}
}
task.resume()
}
This is rather basic and is not 100% fool-proof though. See if it solves your problem.

Resources