2015-09-25 93 views
2

我希望能够通过SwiftyUserDefaults保存包含UIImages的数组,cardImagesPersist Array of Swift

期望的行为

这里是确切所需的行为:

Save an array of UIImages to NSUserDefaults via the SwiftyUserDefault library

Retrieve the images later

代码这被剥离下来到很少的代码

var newPhotoKey = DefaultsKey<NSArray>("image")//Setting up the SwiftyUserDefaults Persisted Array 

     cardImages = [(UIImage(named: "MyImageName.jpg")!)] //This array contains the default value, and will fill up with more 
     Defaults[theKeyForStoringThisArray] = cardImages //This is the persisted array in which the array full of images should be stored. WHERE THE ERROR HAPPENS 

var arrayToRetreiveWith = Defaults[theKeyForStoringThisArray] as! [UIImage] //To Retreive 

错误

我得到以下错误:

Attempt to set a non-property-list object ( ", {300, 300}" ) as an NSUserDefaults/CFPreferences value for key image *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object ( ", {300, 300}" ) for key image'

谢谢!

回答

2

该错误信息是明确的实际。 UIImage不是一个属性列表,因此您需要先将其更改为行数据。我将把下面的例子,但FYI保存像使用NSUserDefaults图像的大数据是不建议。我会使用NSFileManager并将其放在用户文档目录中。反正

var newPhotoKey = DefaultsKey<NSArray>("image") 
cardImages = [(UIImage(named: "MyImageName.jpg")!)] 
var cardImagesRowdataArray: NSData = [] 
for image in cardImages { 
    let imageData = UIImageJPEGRepresentation(image, 1.0) 
    cardImagesRowdataArray.append(imageData) 
} 
Defaults[theKeyForStoringThisArray] = cardImagesRowdataArray 

var arrayToRetreiveWith = Defaults[theKeyForStoringThisArray] as! [NSData] 
// here you can use UIImage(data: data) to get it back 

如果你不使用SwiftyUserDefaults坚持,你可以将它保存在用户文档目录,这里是如何做到这一点

func saveImage(image: UIImage){ 
    if let imageData = UIImageJPEGRepresentation(image, 1.0) { 
     let manager = NSFileManager() 
     if let docUrl = manager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first{ 
      let uniqueName = NSDate.timeIntervalSinceReferenceDate() 
      let url = docUrl.URLByAppendingPathComponent("\(uniqueName).jpg") 
      imageData.writeToURL(url, atomically: true) 
     } 
    } 
} 
2

用户默认值的值必须是属性列表。甲property list

  • 一个字符串(StringNSString),
  • 一个NSData
  • 日期(NSDate),
  • 一个数字(NSNumber),
  • 一个布尔型(也NSNumber) ,
  • 一组属性列表,
  • 或一个字典,其键是字符串,其值是属性列表。

一个UIImage是没有这些的,所以UIImage不是属性列表,并不能成为财产清单的一部分。

您需要将图像转换为NSData才能将其存储为用户默认值。由于UIImage除了包含原始像素数据的一些属性(如scaleimageOrientation),最简单的方法来转换一个UIImageNSData与不亏是由creating an archive

let cardImage: UIImage? = someImage() 
let cardImageArchive: NSData = NSKeyedArchiver.archivedDataWithRootObject(cardImage!) 

您现在可以存储cardImageArchive在较大的属性列表,您可以将其存储为用户默认值。

后来,当你需要重新从数据的图像,这样做:

let cardImageArchive: NSData = dataFromUserDefaults() 
let cardImage: UIImage = NSKeyedUnarchiver.unarchiveObjectWithData(cardImageArchive) as! UIImage