2015-09-25 87 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