Mark.Ben Mark.Ben - 1 year ago 168
Swift Question

NSURL returns nil

Here is my URL:

let urlString = "https://example.com/img/list/mobile/7156-292.jpg"


When I pass it to
NSURL(string: urlString )
it returns
nil
.

I also tried using all
addingPercentEncoding
but got the same result.

FYI: using this urlString
"https://new.domain.com/img/notFound.jpg"
works perfectly.

Any idea what I am doing wrong?

Real code:

let imageCache = NSCache<AnyObject, AnyObject>()

class CustomImageView: UIImageView {
var imageUrlString : String?
var activityIndicatorView : NVActivityIndicatorView?

func loadImageUsingUrlString (urlString : String , activityIndicatorFrame : CGRect , activityIndicatorColor :UIColor){


imageUrlString = urlString;

activityIndicatorView = NVActivityIndicatorView(frame: activityIndicatorFrame,type: NVActivityIndicatorType(rawValue: 29)!)


if let url = URL(string: urlString as String){
let request = URLRequest(url:url as URL)
image = nil;

activityIndicatorView?.color = activityIndicatorColor
self.addSubview(activityIndicatorView!)
activityIndicatorView?.startAnimating();

if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage{

self.activityIndicatorView?.stopAnimating();
for view in self.subviews{
view.removeFromSuperview()
}
self.image = imageFromCache
return;
}

URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
if error != nil {
return ;
}

DispatchQueue.main.async{
if let imageData = data{
let imageToCache = UIImage(data: imageData)

if self.imageUrlString == urlString {
self.activityIndicatorView?.stopAnimating();
for view in self.subviews{
view.removeFromSuperview()
}
self.image = imageToCache
}
if imageToCache != nil{
imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)
}else{
self.image = UIImage(named:"Keylead");
}

self.activityIndicatorView?.stopAnimating();
}

}
}).resume()
}else {
print("Convert urlString: \(urlString) returns nil")
self.image = UIImage(named: "notFound")
}

}
}


Below is what I am getting:

Convert urlString: https://example.com/images/list/mobile/23060-8.jpg returns nil
Convert urlString: https://example.com/images/list/mobile/49012-8.jpg returns nil
Convert urlString: https://example.com/images/list/mobile/49014-8.jpg returns nil
Convert urlString: https://example.com/images/list/mobile/7156-188.JPG returns nil


The function call is happening inside a custom cell. I assume this amount of code would be enough for you guys since I get the
urlString printed
in
else
.

Answer Source

Your updated output explains your issue. There is a newline character at the end of urlString. You need to cleanup the string from wherever you are obtaining those URLs.

let cleanURL = badURL.trimmingCharacters(in: . whitespacesAndNewlines)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download