Nsurl Found Nil While Unwraping an Optional Value

NSURL found nil while unwraping an Optional value

The | character its not a valid URL character so you must replace it with percent escape character. Encoding whole string will do that automatically for you

var stringUrl = "https://roads.googleapis.com/v1/snapToRoads?path=-35.27801,149.12958|-35.28032,149.12907"

let URL = NSURL(string: stringUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!

Fatal Error: Unexpectedly found nil while unwrapping an Optional value NSURL

From Apples documentation on NSData(contentsOfURL)

Do not use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.

If your app crashes because of this it will be rejected from the store.

Instead you should use NSURLSession. With the Async callback block as in my example.
Also it is not a good idea to force unwrap optionals ! as you will get run time errors instead use the if let syntax

See my example below.

if let photo = selectedPhoto{
let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(photo)")
if let url = photoUrl{
NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {(data, response, error) in
if let d = data{
dispatch_async(dispatch_get_main_queue(), {
if let image = UIImage(data: d) {
self.yemekResim.image = image
}
})


}
}).resume()
}
}
}

Unexpectedly found nil while unwrapping an Optional value - NSMutableURLRequest

You must encode your url as it contains special characters.

try this

let urlWithParams = "http://192.168.0.4:3003/manager/all"
let urlStr = urlWithParams.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! // or use let urlStr = urlWithParams.stringByAddingPercentEncodingWithAllowedCharacters(.URLQ‌​ueryAllowedCharacter‌​Set())
let request = NSMutableURLRequest(URL: NSURL(string: urlStr)!)

for more reference see the Apple Documents

SwiftUI, Fatal error: Unexpectedly found nil while unwrapping an Optional value

url could still be nil, if urlString doesn't represent a valid URL. You haven't guarded against that; you've only guarded against urlString not being nil.

You need to guard against both possible outcomes:

func loadImageFromUrl() {

guard let url = URL(string: self.urlString) else {
print("Invalid url string: \(self.urlString)")
return
}

let task = URLSession.shared.dataTask(with: url, ....

// rest of your code
}

Of course, that doesn't solve the underlying problem that urlString is indeed broken. You need to see what's going on there.

Since you're visually seeing that it's correct, it's possible that it contains some whitespace at the beginning or the end. If it's not a urlString that you control, you can trim it:

let trimmedUrlStr = self.urlString.trimmingCharacters(in: .whitespacesAndNewlines)

Unexpectedly found nil while unwrapping an Optional value even though it has a value assigned

The exception does not mean that url is nil, but URL(string:url) is nil

You need to check if the url string is a valid url:

private func getData(from url: String) {
guard let theURL = URL(string: url) else { print ("oops"); return }
let getfromurl = URLSession.shared.dataTask(with: theURL, completionHandler: {data, response, error in
/* ... */
}
}

Update

Since the url string is now given: The problem are the curly braces; they are marked as unsafe in RFC1738 and should be replaced by %7b (opening) and %7d (closing), hence:

let url = "https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure=%7b%22date%22:%22date%22,%22areaName%22:%22areaName%22,%22areaCode%22:%22areaCode%22,%22newCasesByPublishDate%22:%22newCasesByPublishDate%22,%22cumCasesByPublishDate%22:%22cumCasesByPublishDate%22,%22newDeathsByDeathDate%22:%22newDeathsByDeathDate%22,%22cumDeathsByDeathDate%22:%22cumDeathsByDeathDate%22%7d"

let theUrl = URL(string: url)
print (theUrl)

This is also an example in the official API documentation:

curl -si 'https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure=%7B%22name%22:%22areaName%22%7D'

URL - Found nil while unwrapping an Optional value

The reason that it is failing is that there are hidden Unicode characters in your string. Copying and pasting the url string you provided into a hidden Unicode character checker gives the following for your url

http://blahblahblah.blah.net/apiU+200B​/friendgroups​U+200B/1c8264b95884409f90b4fd8ba9d830e1

Notice the additional hidden characters at the end of the words api and friendgroups

You can try it here https://www.soscisurvey.de/tools/view-chars.php

URL Error : Unexpectedly found nil while unwrapping an Optional value: file

Modify your for loop like this

for item in gifsa {
guard let url = URL(string : item) else {continue}
//Rest of the code here
}

Try not to force unwrap if you're unsure of the values. :)

Fatal error: Unexpectedly found nil while unwrapping an Optional value SwiftUI AnimatedImage

The issue is that you're comparing an unwrapped value with nil. Your program crashes even before the comparison.

You need to compare an optional value instead:

if (URL(string: item.img) != nil) { ... }

Better even to use if-let to make sure that url is not nil:

Button(action: {}) {
if let url = URL(string: item.img) {
AnimatedImage(url: url)
.resizable()
.frame(height: 425)
.padding(.bottom, 15)
.cornerRadius(5)
}
}

Unexpectedly found nil while unwrapping an Optional value. Xcode cannot find videoURL from bundle

Always use

if let videoUrl = Bundle.main.url(forResource:"video",withExtension:"mp4") { --- }

And verify target memberShip is ticked for the asset video.mp4



Related Topics



Leave a reply



Submit