NSURLConnection finished with error - code -1002 when retrieving and displaying images - ios

For anyone having this problem, who is not helped by this post, you may find the following use-full: Here.
Here is a copy of the error:
2018-08-29 18:39:59.458950-0400 proj[5319:3378682] NSURLConnection finished with error - code -1002
I have looked through these answer and not found anything to work. I believe its because the problem is happening for another reason for those. I am having the problem when fetching images from a database and trying to display them in on a image view.
Full code bellow:
import UIKit
import FirebaseStorage
import FirebaseDatabase
import FirebaseAuth
import Firebase
class PhaseOneViewController: UIViewController {
#IBOutlet weak var p1ImageView: UIImageView!
#IBAction func loadImages(_ sender: Any) {
//p1ImageView.image = nil
NKPlaceholderImage(image: UIImage(named: "placeholder"), imageView: p1ImageView, imgUrl: "\(Storage.storage().reference().child((Auth.auth().currentUser?.uid)!).child("post\(takePicViewController().finalPost + PhotoArray.sharedInstance.numberPost)").child(ImageUploadManager().imageName))") { (image) in }
}
func NKPlaceholderImage(image:UIImage?, imageView:UIImageView?,imgUrl:String,compate:#escaping (UIImage?) -> Void) {
if image != nil && imageView != nil {
imageView!.image = image!
}
var urlcatch = imgUrl.replacingOccurrences(of: "/", with: "#")
let documentpath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
urlcatch = documentpath + "/" + "\(urlcatch)"
let image = UIImage(contentsOfFile:urlcatch)
if image != nil && imageView != nil
{
imageView!.image = image!
compate(image)
}else{
if let url = URL(string: imgUrl){
DispatchQueue.global(qos: .background).async {
() -> Void in
let imgdata = NSData(contentsOf: url)
DispatchQueue.main.async {
() -> Void in
imgdata?.write(toFile: urlcatch, atomically: true)
let image = UIImage(contentsOfFile:urlcatch)
compate(image)
if image != nil {
if imageView != nil {
imageView!.image = image!
}
}
}
}
}
}
}
}
I have also asked These questions Link, Link, which may be of help to someone in my situation or to solve this problem.
Thanks!

Related

How i can see the image inside UIImageView?

I have an array filled with parsed json data including image url's. But when i try to see that images inside uiimageview, it doesn't the show. What should i do
I printed the url. This is my url inside array.
This is my array
var feedResult = [Result]()
It shows the name inside collectionview but i couldn't see the images. I used named like everybody does. But what is missing?
let info = feedResult[indexPath.row]
cell.appLabel.text = info.artistName
cell.customCollectionImage.image = UIImage(named: info.artWorkUrl)
You have to download the image Data using the url you got, only then you will use the downloaded data, like so:
imageView.image = UIImage(data: downloadedData)
Here is a quick subclass of UIImageView that does the downloading:
class URLImageView: UIImageView {
func download(url urlString: String) {
guard let url = URL(string: urlString) else { return }
let task = URLSession.shared.dataTask(with: url) { (downloadedData, _, error) in
guard error == nil && downloadedData != nil else { return }
DispatchQueue.main.async{
self.image = UIImage(data: downloadedData!)
}
}
task.resume()
}
}
Update-1 Use the download function using UIImageView extension, without subclassing, like so:
extension UIImageView {
func download(url urlString: String) {
guard let url = URL(string: urlString) else { return }
let task = URLSession.shared.dataTask(with: url) { (downloadedData, _, error) in
guard error == nil && downloadedData != nil else { return }
DispatchQueue.main.async{
self.image = UIImage(data: downloadedData!)
}
}
task.resume()
}
}
Usage:
cell.customCollectionImage.download(url: info.artWorkUrl)
By using UIImage(named: info.artWorkUrl) you are not accessing the image in your array but the images in your Assets.xcassets (assets that you add manually in your project).
You need to download the image from the artWorkUrl and then directly use the downloaded image like this:
cell.customCollectionImage.image = UIImage(data: yourImageData)
Where yourImageData is what you have downloaded from the server with the artWorkUrl.

How to add flag image from an API?

import UIKit
class DetailsViewController: UIViewController {
#IBOutlet weak var alpha3CodeLbl: UILabel!
#IBOutlet weak var regionLbl: UILabel!
#IBOutlet weak var flagImage: UIImageView!
var countrie:jsonStruct?
override func viewDidLoad() {
super.viewDidLoad()
alpha3CodeLbl.text = countrie?.alpha3Code
regionLbl.text = countrie?.region
let urlString = "http://restcountries.eu/rest/v2/all" + (countrie?.flag)!
flagImage.downloadedFrom(url: url!)
}
}
extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloadedFrom(url: url, contentMode: mode)
}
}
I'm trying to get the flag image form this API http://restcountries.eu/rest/v2/all
There is no error but the image does not appear. But there is no result if there anyone here can fix this issue.
Please, not that everything is okay and try to get the image in too many ways but still no result.
Also, I try this
let urlString = "http[enter image description
here][1]://restcountries.eu" + (countrie?.flag)!
A few things to fix. You should test the url before using it.
let str = "yourURL"
guard let theUrl = URL(string: str) else { return }
As mentioned by #rmaddy in a comment above, UIImage isn't going to work with SVG files. Use a UIWebView instead
var request = URLRequest(url:theUrl)
webView.loadRequest(request)
Or try SVGKit to convert SVG as described here

Swift Image Cache not Reloading

I'm having problems cacheing for images from JSON correctly with this UIImageView extension. The images load correctly when I first open the app and scroll down the page. However when I scroll back up, they don't reload and are completely gone. Can anyone see anything wrong with the code?
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
func loadImageUsingUrlString(urlString: String) {
let url = NSURL(string: urlString)
if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = imageFromCache
return
}
URLSession.shared.dataTask(with: url! as URL) { (data, response, error) in
if error != nil {
print(error ?? "URLSession error")
return
}
DispatchQueue.main.async {
let imageToCache = UIImage(data: data!)
imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)
self.image = imageToCache
}
}.resume()
}
}
Here is the snippet from the cell.swift file
let imageCache = NSCache<AnyObject, AnyObject>()
func setupThumbnailImage() {
if let thumbnailImageUrl = television?.poster_url {
let urlPrefix = "https://www.what-song.com"
let urlSuffix = thumbnailImageUrl
let urlCombined = urlPrefix + urlSuffix
thumbnailImageView.loadImageUsingUrlString(urlString: urlCombined)
}
}
I suggest using kingFisher, it is very easy to use and it manages all starting from cache threads etc.
let imageResource = ImageResource(downloadURL:URL(string: imagePath )!,cacheKey: imagePath )
viewImage.kf.indicatorType = .activity
viewImage.kf.setImage(with: resource)
where imagePath is the url of your image and viewImage is your imageView
Most probably you would be calling it in wrong way.
Remember that in tableView you reuse the cells.
By the time response comes back for the URLSessionTask you would have already scrolled up/down. In that case self.image would be assigned to the currently visible cell.
Please add your cellForRow code in question.

Adding new UIImage to SubView takes very long

In my first swift project I face some problems by adding a new UIImage to the SubView after downloading the content of this image.
It looks like the download is done pretty fast but the App needs another 5-15 seconds to update the view. I have no clue why.
Here is what I have done:
override func viewDidLoad() {
super.viewDidLoad()
//...
loadPic(PrevPic)
}
func loadPic(prevImage: UIImageView){
//... get URL; result in object["data"]
let fileUrl = NSURL(string: object["data"] as! String)
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: fileUrl!)
let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if error != nil {
print(error!.localizedDescription)
} else {
var imagePic: UIImageView?
let imageData = NSData(data: data!)
prevImage.removeFromSuperview()
let image: UIImage = UIImage(data: imageData)!
imagePic = UIImageView(image: image)
imagePic?.contentMode = .ScaleAspectFit
self.view.addSubview(imagePic!)
//... alignment
}
}
task.resume()
//...
}
An ideas why?
Thanks for the support.
You dont have to remove UIImageView from your view and add it back. That is taking a lot of time. You should replace imageView's old image with new one.You can use following code.
if let newImage = UIImage(data: imageData){
imageView.image = newImage
}
When call for the web service then the task execute on main thread thats why the UI become freeze and none responsive. To get rid of this problem call the main queue and the update the UI like this:
func loadPic(prevImage: UIImageView){
//... get URL; result in object["data"]
let fileUrl = NSURL(string: object["data"] as! String)
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: fileUrl!)
let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if error != nil {
print(error!.localizedDescription)
} else {
var imagePic: UIImageView?
let imageData = NSData(data: data!)
dispatch_async(dispatch_get_main_queue(), {
prevImage.removeFromSuperview()
let image: UIImage = UIImage(data: imageData)!
imagePic = UIImageView(image: image)
imagePic?.contentMode = .ScaleAspectFit
self.view.addSubview(imagePic!)
//... alignment
})
}
}
task.resume()
//...
}
The basic idea is
dispatch_async(dispatch_get_main_queue(), {
// update UI
})

Downloaded image not being displayed iOS Swift

I'm just starting to learn how to make network requests in iOS Swift. Below is a very simple image request where everything seems to be working. The task downloads the image with no errors but the imageView never displays the downloaded image. Any help would be greatly appreciated.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let imageURL = NSURL(string: "https://en.wikipedia.org/wiki/Baseball#/media/File:Angels_Stadium.JPG")!
let task = NSURLSession.sharedSession().dataTaskWithURL(imageURL) { (data, response, error) in
if error == nil {
let downloadedImage = UIImage(data: data!)
performUIUpdatesOnMain {
self.imageView.image = downloadedImage
}
}
}
task.resume()
}
}
Your code is working fine except for the fact you're using a wrong URL and for that your downloadedImage is coming nil because it can't create an UIImage for this data, the correct URL is:
https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Angels_Stadium.JPG/1920px-Angels_Stadium.JPG
Update your code code as the above code and everything should be work fine:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let imageURL = NSURL(string: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Angels_Stadium.JPG/1920px-Angels_Stadium.JPG")!
let task = NSURLSession.sharedSession().dataTaskWithURL(imageURL) { (data, response, error) in
guard error == nil, let data = data else { return }
let downloadedImage = UIImage(data: data)
dispatch_async(dispatch_get_main_queue()) {
self.imageView.image = downloadedImage
}
}
task.resume()
}
I hope this help you.
If you are getting an error from NSURLSession your current code would fail silently. Don't do that.
Add a print statement inside your data task's completion block that logs the value of error and of data. Also log downloadedImage once you convert data to an image.
Finally, show us the code for your performUIUpdatesOnMain function.

Resources