iOS Keep url array order when saving images into a

2019-07-28 05:39发布

问题:

I'm trying to do the following.
I have an array that contains several URLs for different images. These images will be displayed into a scrollview and I want to keep this order to be able to delete specific images at a specific index.
Right now I'm using a for loop, first I load the array with NSNull objects and afterward I run the loop replacing all the objects with images. This doesn't seem to be really efficient, specially when the app loads from the background.

This is my code:

func downloadImagesfromUrlArray(){

    for var i=0;i < graphsURLlist.count; i++ {
        if let data = NSData(contentsOfURL: graphsURLlist[i]){
            let image = UIImage(data: data)
            pageImages.replaceObjectAtIndex(i, withObject: image!)
            //self.scaleImagesandScrollView()
        }else{
            NSLog("%@", i)
            var alert = myAlertController(title: nil, message: "Error trying to update the charts. Try again later \(i)",
                preferredStyle: UIAlertControllerStyle.Alert)


            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
        //Enter queue for every image to download
    }

    dispatch_group_leave(self.group)
}

Is there a better approach to do this? Thanks

回答1:

You better want to download images asynchronously and cache them. Before the images are downloaded it's better to display spinner, and then replace it with an image.

Here are a few related methods from my latest app:

func downloadAndCacheImg(url: String?, cell: AppCell, tableView: UITableView, indexPath: NSIndexPath) {
    if url == nil { return }

    let charactersToRemove = NSCharacterSet.alphanumericCharacterSet().invertedSet
    let cacheFilename = "".join(url!.componentsSeparatedByCharactersInSet(charactersToRemove))

    if let fullFilename = prefixFilenameWithDirectory(cacheFilename), img = UIImage(named: fullFilename) {
        cell.setAppImage(img)
        return
    }
    if let nsUrl = NSURL(string: url!) {
        NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: nsUrl), queue: NSOperationQueue.mainQueue(), completionHandler: { (response, data, error) -> Void in
            if let data = data, img = UIImage(data: data) {
                if let fullFilename = self.prefixFilenameWithDirectory(cacheFilename) {
                    data.writeToFile(fullFilename, atomically: true)
                }
                if let cell = tableView.cellForRowAtIndexPath(indexPath) as? AppCell {
                    cell.setAppImage(img)
                }
            }
        })
    }
}

func prefixFilenameWithDirectory(filename: String) -> String? {
    var dir = NSFileManager.defaultManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true, error: nil)
    dir = dir?.URLByAppendingPathComponent(filename)
    return dir?.path
}


标签: ios swift ios8