0

I tried to download several image from itunes api using asynchronous request, I already stored the image url on array. But when I download the image and put it on new array the images order become random.

Here is my code:

      for appDict in appArray {
            let songCoverUrl: String? = appDict["im:image"][0]["label"].string


            let largerImageUrl = songCoverUrl!.stringByReplacingOccurrencesOfString("55x55", withString: "400x400")

                if largerImageUrl.isEmpty == false {

                    let url : NSURL = NSURL(string: largerImageUrl)!

                        let request : NSURLRequest = NSURLRequest(URL: url)

                    NSURLSession.sharedSession().dataTaskWithRequest(request){ (imagedata:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
                        if error == nil {

                            let image : UIImage = UIImage(data: imagedata!)!
                            self.coverArray.append(image)

                        }else{

                            let image : UIImage = UIImage(named: "noArtworkImage.png")!
                            self.coverArray.append(image)

                        }
                    }.resume()

                }
        }

How can I keep the order of the images as the array of url?

Ega Setya Putra
  • 1,645
  • 6
  • 23
  • 51

1 Answers1

3

You need to store the original order of the songCoverUrl objects.

I would suggest one of two ways, pre-create your array and using [Image?] allow nil entries that aren't downloaded yet and simply go:

myArray[indexOfImagesUrlInOriginalList] = justDownloadedImage.

OR along similar lines using a dictionary with the INDEX pre-done. [NSInteger : UIImage] and again find the index of the url once it is successfully downloaded (using response.request.url)

or perhaps more neatly tie the imageUrl to image via:

let lookup = [String : UIImage]()
look[myImageUrl] = justDownloadedImage

and then do a sort.

Infact either way will require you to retrieve the URL upon successful completion and then search the original array of items to find the index. You could infect create a lookup [String : NSInteger] whereby it is myLookup[currentUrl] = i (where i is the index looped before downloading)

    var indexLookup = [String : Integer]()  
    for index,appDict in enumerate(appArray) {
        let songCoverUrl: String? = appDict["im:image"][0]["label"].string
        let largerImageUrl = songCoverUrl!.stringByReplacingOccurrencesOfString("55x55", withString: "400x400")
        indexLookup[index] = largerImageUrl
        //....
    }
Mitchell Currie
  • 2,769
  • 3
  • 20
  • 26
  • I tried `self.coverArray[index] = image` but I got **fatal error: Array index out of range**. What did I do wrong? – Ega Setya Putra Oct 27 '15 at 06:31
  • If you wish to use the array you have to pre fill it. I.e add one nil entry for each type when your array is an optional type – Mitchell Currie Oct 27 '15 at 06:36
  • my array declaration it's like this `var coverArray : [UIImage?] = []` , how can i add one nil entry? – Ega Setya Putra Oct 27 '15 at 06:47
  • Now go myArray.append(nil) for as many times as you have objects? – Mitchell Currie Oct 27 '15 at 06:48
  • There are many ways. You could also create a tuple (Url,Image?) and create one for each image and then come back and assign the image property lately, in swift we have much better syntax than objective-c. Of course by that I mean your array would be of tuples. Pick which you feel is easiest to understand – Mitchell Currie Oct 27 '15 at 06:52