问题
I am writing an iOS app in Swift and the app collects user input from multiple app screens and in the last screen its supposed to POST the information collected to the server via API.
Now my question is, what is the best way to manage the collected data on the app? Should I use plist to save my form data ? It also has one image which I want to upload to my server from the final screen. How should I go about this?
PS: I also read about http://developer.apple.com/CoreData, but I'm not sure if this is the right way to go forward.
Any suggestion is greatly appreciated.
回答1:
UPDATE: to save your time - this is Swift 1.2 solution. I didn't test it on Swift 2 (likely secureValue flow have to be updated)
Looks like you are talking about user's details/profile (correct me if I wrong), for this amount of data - using NSUserDefault is totally ok.
For user preferences (if that the case!!) I would use something like Preference Manager:
import Foundation
import Security
class PreferencesManager {
class func saveValue(value: AnyObject?, key: String) {
NSUserDefaults.standardUserDefaults().setObject(value, forKey: key)
NSUserDefaults.standardUserDefaults().synchronize()
}
class func loadValueForKey(key: String) -> AnyObject? {
let r : AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey(key)
return r
}
class func saveSecureValue(value: String?, key: String) {
var dict = dictForKey(key)
if let v = value {
var data: NSData = v.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
(SecItemDelete(dict as NSDictionary as CFDictionary))
dict[kSecValueData as NSString] = v.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion:false);
var status = SecItemAdd(dict as NSDictionary as CFDictionary, nil)
} else {
var status = SecItemDelete(dict as NSDictionary as CFDictionary)
}
}
class func loadSecureValueForKey(key: String) -> String? {
var dict = dictForKey(key)
dict[kSecReturnData as NSString] = kCFBooleanTrue
var dataRef: Unmanaged<AnyObject>?
var value: NSString? = nil
var status = SecItemCopyMatching(dict as NSDictionary as CFDictionary, &dataRef)
if 0 == status {
let opaque = dataRef?.toOpaque()
if let op = opaque {
value = NSString(data: Unmanaged<NSData>.fromOpaque(op).takeUnretainedValue(),
encoding: NSUTF8StringEncoding)
}
}
let val :String? = value as? String
return val
}
class private func dictForKey(key: String) -> NSMutableDictionary {
var dict = NSMutableDictionary()
dict[kSecClass as NSString] = kSecClassGenericPassword as NSString
dict[kSecAttrService as NSString] = key
return dict
}
}
You can use
PreferencesManager.saveSecureValue
for secure data (like password etc) and
PreferencesManager.saveValue
for the rest of values
来源:https://stackoverflow.com/questions/32307648/storing-data-in-swift-ios-app-for-later-use