如何使用UserDefaults保存UIButton图像?

时间:2019-03-20 12:51:56

标签: swift

我想在UserDefaults中保存一个UIButton图像,并稍后在我的代码中使用一个键对其进行检索。 UIImage来自UIPickerView正在使用的元组。

let defaults = UserDefaults.standard

@IBOutlet weak var topCurrencyPicker: UIPickerView!

var topPickerOptions = [
    (symbol: String, name: String, sign: String, flag: UIImage)]()

func createTopAndBottomCurrency() {
    let topUserIndex = topCurrencyPicker.selectedRow(inComponent: 0)
    let topUserChoice = money.currencyISOCode[topUserIndex]
    userCurrencyChoice = Currencies(top: topUserChoice, bottom: bottomUserChoice)

// Save user pickerViews Choice
    defaults.set(topUserIndex,
                 forKey: ExchangePreferencesVC.topExPickerKey)
    defaults.set(userCurrencyChoice.top.sign,
                 forKey: ExchangePreferencesVC.topExSignKey)
    defaults.set(userCurrencyChoice.top.symbol,
                 forKey: ExchangePreferencesVC.topExSymbolKey)
}

然后可以像保存String一样容易地保存此UIImage吗?

1 个答案:

答案 0 :(得分:-1)

Swift 4.2

let returnedAnnotationView:MKPinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier:"PinAnnotation")
returnedAnnotationView.animatesDrop = true
returnedAnnotationView.canShowCallout = true
return returnedAnnotationView

更好地将图像存储在文档目录中。 如果需要存储UserDefaults,则可以像存储数据一样存储它。

用法

public final class PreferencesService {
  private let userDefaults: UserDefaults

  init(userDefaults: UserDefaults = .standard) {
    self.userDefaults = userDefaults
  }

  var avatar: UIImage? {
    get {
        guard let filename = documentsDirectory?.appendingPathComponent(#function, isDirectory: false) else {
            return nil
        }
        return UIImage(contentsOfFile: filename.path)
    }
    set {
        guard let filename = documentsDirectory?.appendingPathComponent(#function, isDirectory: false) else {
            return
        }
        guard let newImage = newValue else {
            try? FileManager.default.removeItem(at: filename)
            return
        }
        if let data = newImage.jpegData(compressionQuality: 1.0) {
            try? data.write(to: filename)
        }
    }
  }

  private var documentsDirectory: URL? {
      let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
      return paths.first
  }

  var coolDown: Bool {
      get { return userDefaults.bool(forKey: #function) }
      set { userDefaults.set(newValue, forKey: #function) }
  }

  var lastVisited: Date {
      get { return userDefaults.object(forKey: #function) as? Date ?? Date() }
      set { userDefaults.set(newValue, forKey: #function) }
  }

}

奖金::请注意如何简单地存储其他类型的布尔,日期,字符串。