Appending Images in Array

2019-07-29 19:23发布

问题:

I am trying to append images in array after downloading from XML enclosure. 20 images are in XML. I want to store these images one by one in array in order form, and then trying to save in NSUserDefaults. Can any one please tell me how i can do this? Thanks

 var imageArray : [NSData] = []
    var imgIndex = 0

downloadFileFromURL(NSURL(string: self.posts.objectAtIndex(indexPath.row).valueForKey("enclosure") as! String)!, completionHandler:{(img) in
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    cell.sideImageView.image = img


                    if indexPath.row == self.imgIndex{
                    imageArray.insert(UIImageJPEGRepresentation(img, 0.75)!, atIndex: self.imgIndex)
                    self.imgIndex++
                    print("Image append with data")
                    self.newsDefaults.setObject(imageArray, forKey: "image")
                    }


                })
            })


    func downloadFileFromURL(url1: NSURL?,completionHandler: CompletionHandler) {
        // download code.
        if let url = url1{
            let priority = DISPATCH_QUEUE_PRIORITY_HIGH
            dispatch_async(dispatch_get_global_queue(priority, 0)) {
                let data = NSData(contentsOfURL: url)
                if data != nil {
                    print("image downloaded")
                    completionHandler(image: UIImage(data: data!)!)
                }
            }
        }
    }

'I am getting this error after some output. image downloaded image downloaded Image append with data fatal error: Array index out of range'

回答1:

Get all images and assign to

var DtaAryVar: [NSData]()

Then convert array of NSData to Data and store

let DtaZipVar = NSKeyedArchiver.archivedDataWithRootObject(DtaAryVar)

let DftSdbVal = NSUserDefaults.standardUserDefaults()
DftSdbVal.setObject(DtaZipVar, forKey: "ImageKey")

You can get back ur data by

var DtaZipVar = DftSdbVal.valueForKey("ImageKey")
let DtaAryVar = NSKeyedUnarchiver.unarchiveObjectWithData(DtaZipVar) as! [NSData]

let ImjAryVar = [UIImage]()
for DtaIdxVar in DtaAryVar
{
    ImjAryVar.append(UIImage(data : DtaIdxVar))
}