简体   繁体   中英

How download image from url and append UIImageView array (iOS)

@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var imgPicker: UIPickerView!

let PICKER_VIEW_COLUMN = 1
let PICKER_VIEW_HEIGHT: CGFloat = 80
var imageArray = [UIImage?]()
var imageFileName = ["dongbinggo1.png","dongbinggo2.png","dongbinggo3.png"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    for i in 0..<imageFileName.count{
        downLoadItems(imageFileName[i])
    }
    imgView.image = imageArray[0]
}
func downLoadItems(_ imgName: String){
    let url = URL(string: "http://(myIP)/test/\(imgName)")!
    let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)

    let task = defaultSession.dataTask(with: url){(data, response, error) in
        if error != nil{
            print("Failed to download data")
        }else{
            DispatchQueue.main.async{
                let image = UIImage(data: data!)!
                self.imageArray.append(image)
            }
            print("Data is downloaded")
        }
    }
    task.resume()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return PICKER_VIEW_COLUMN
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
    return PICKER_VIEW_HEIGHT
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return imageFileName.count
}

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    let imageView = UIImageView(image: imageArray[row])
    imageView.frame = CGRect(x:0,y:0,width: 50, height: 50)

    return imageView
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    imgView.image = imageArray[row]
}

I want to download images from url and insert UIPickerView and choose pick and then show in UIImageView . I think appending UIImage Array after all images have been downloaded.

I don't know how to insert the code and where to insert it.

You tried to use MAX_ARRAY_NUM but your imageFileName only contains 3 filenames. And imageArray is an empty array but you try to get 0 index value that is not present on the array.

These are the main issue.

var imageArray = [UIImageView?]()
var imageFileName = ["dongbinggo1.png","dongbinggo2.png","dongbinggo3.png"]

 for i in 0..<imageFileName.count {
      downLoadItems(imageFileName[i])
 }

if let imgView = imageArray[0] { 
     self.imgView = imgView
 } 

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