在阵列中附加图像

时间:2016-06-26 04:31:06

标签: ios swift swift2 nsuserdefaults

我尝试从XML enclosure下载后将图片附加到数组中。 XML中有20张图片。我想按顺序将这些图像逐个存储在数组中,然后尝试保存在NSUserDefaults中。 任何人都可以告诉我怎么做到这一点? 感谢

 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!)!)
                }
            }
        }
    }

'在输出后我收到此错误。图像下载 图像下载 图像附加数据 致命错误:数组索引超出范围'

1 个答案:

答案 0 :(得分:0)

获取所有图像并分配到

var DtaAryVar: [NSData]()

然后将NSData数组转换为数据并存储

let DtaZipVar = NSKeyedArchiver.archivedDataWithRootObject(DtaAryVar)

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

您可以通过

获取您的数据
var DtaZipVar = DftSdbVal.valueForKey("ImageKey")
let DtaAryVar = NSKeyedUnarchiver.unarchiveObjectWithData(DtaZipVar) as! [NSData]

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