简体   繁体   中英

NSURLErrorDomain with code=-1100

I was trying to download a picture to my app from

在此处输入图片说明 The request failed with the error NSURLErrorDomain and the code is really -1100. The url should be correct since I checked it in the browser. Anyone knows why?

let userImageURL: String! = "http://i.imgur.com/QhCzQoR.jpg";
let url = NSURL(fileURLWithPath: userImageURL);
let request:NSURLRequest = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: { (response:NSURLResponse!, imageData:NSData!, error:NSError!) -> Void in
                let image = UIImage(data: imageData!);
 })

The reason you are getting this problem is because you have used

let url = NSURL(fileURLWithPath: userImageURL);

Instead you should use:

let url = NSURL(string: userImageUrl)

I code in Objective-C, it should be easy to convert it in Swift (small modification in fact, but the explanation is not that much related to code). If you check the error complete message, you'll get:

Error Domain=NSURLErrorDomain Code=-1100 "The requested URL was not found on this server." UserInfo=0x7997b7e0 {NSErrorFailingURLStringKey=file:///http:/i.imgur.com/QhCzQoR.jpg, NSErrorFailingURLKey=file:///http:/i.imgur.com/QhCzQoR.jpg, NSLocalizedDescription=The requested URL was not found on this server., NSUnderlyingError=0x799f3080 "The requested URL was not found on this server."}

Clearly, if you look carefully at the URL, you have file:///http:/i.imgur.com/QhCzQoR.jpg , which is not the URL wanted. If you log url.absoluteString , you'll see it to your URL, it's you that set it like this.

Why? Because you used fileURLWithPath: instead of URLWithString: . So change your line with:

let url = NSURL(URLWithString: userImageURL);

Some discussions about the differences between theses two: What is difference between URLWithString and fileURLWithPath of NSURL? or the doc .

Update: In Swift 4:

let url = URL(string: userImageURL)

We also recommend from Swift3+ to avoid NSStuff when there is Swift Equivalent: NSURL => URL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM