Reputation: 253
I have a detailviewcontroller file in which I have an imageview a textfield, a textview, a date picker. image view image is getting me from first controller. when i fill up rest data like textfield, textview, select date, then when I click on save button in navigation bar then the data should be saved in nsuserdefault and pass onto tableview of another controller. again when I start the app and fill the details again then that data plus previous data should also be there. don't know how to do
my detailviewcontroller file:
class DetailsViewController: UIViewController{
var picker : UIDatePicker = UIDatePicker()
@IBOutlet weak var selectedDate: UIButton!
@IBOutlet weak var detailsVCImage: UIImageView!
@IBOutlet weak var geoAddressLabel: UILabel!
@IBOutlet weak var titleTF: UITextField!
@IBOutlet weak var notesTextView: CustomTextView!
var mapView:GMSMapView!
var transferedImage:UIImage!
var arrayList = [[String:Any]]()
var obj = [String:Any]()
override func viewDidLoad() {
super.viewDidLoad()
notesTextView.text = "Please enter Notes...."
notesTextView.textColor = .lightGray
detailsVCImage.image = transferedImage
hideKeyboardWhenTapped()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
dismiss(animated: true)
}
@IBAction func datePickerTapped(_ sender: Any) {
picker.datePickerMode = UIDatePickerMode.dateAndTime
picker.addTarget(self, action: #selector(dueDateChanged(sender:)), for: UIControlEvents.valueChanged)
// self.picker = UIDatePicker(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 85))
let pickerSize : CGSize = picker.sizeThatFits(CGSize.zero)
picker.frame = CGRect(x:0.0, y:442, width:pickerSize.width, height:85)
//width: 288
self.view.addSubview(picker)
}
@objc func dueDateChanged(sender:UIDatePicker){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
selectedDate.setTitle(dateFormatter.string(from: sender.date), for: .normal)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
picker.removeFromSuperview()
}
@IBAction func saveDataTaopped(_ sender: Any) {
obj["title"] = titleTF.text
obj["notes"] = notesTextView.text
obj["image"] = transferedImage
obj["date"] = selectedDate
arrayList.append(obj)
}
func reverseGeocodeCoordinate(_ coordinate: CLLocationCoordinate2D) {
let geocoder = GMSGeocoder()
geocoder.reverseGeocodeCoordinate(coordinate) { response, error in
// self.geoAddressLabel.unlock()
guard let address = response?.firstResult(), let lines = address.lines else {
return
}
self.geoAddressLabel.text = lines.joined(separator: "\n")
let labelHeight = self.geoAddressLabel.intrinsicContentSize.height
//// self.mapView.padding = UIEdgeInsets(top: self.view.safeAreaInsets.top, left: 0,
// bottom: labelHeight, right: 0)
//
// UIView.animate(withDuration: 0.25) {
// self.pinImageVerticalConstraint.constant = ((labelHeight - self.view.safeAreaInsets.top) * 0.5)
// self.view.layoutIfNeeded()
// }
}
}
@IBAction func getLocationAddress(_ sender: Any) {
// reverseGeocodeCoordinate(target)
}
}
extension DetailsViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func hideKeyboardWhenTapped () {
let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(DetailsViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
extension DetailsViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
// reverseGeocodeCoordinate(position.target)
}
// func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {
// geoAddressLabel.lock()
//
// if (gesture) {
// mapCenterPinImage.fadeIn(0.25)
// mapView.selectedMarker = nil
// }
// }
}
my listtableviewcontroller file:
class ListTableViewController: UITableViewController {
@IBOutlet weak var listImage: UIImageView!
@IBOutlet weak var listTitle: UILabel!
@IBOutlet weak var listNotes: UITextView!
@IBOutlet weak var listDate: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
Upvotes: 1
Views: 1757
Reputation: 960
Using Core Data
ViewController.swift
import UIKit
import CoreData
class ViewController: UIViewController {
@IBOutlet weak var imgVw: UIImageView!
@IBOutlet weak var titleTxt: UITextField!
@IBOutlet weak var descTxt: UITextView!
@IBOutlet weak var dateTxt: UIDatePicker!
var idd: UInt64 = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.clearContent()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(
dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
@IBAction func SaveClk(_ sender: Any) {
idd = Date().ticks
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Product", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)
let imageData: NSData = (imgVw.image)!.pngData()! as NSData
newUser.setValue(dateTxt.date, forKey: "pDate")
newUser.setValue(descTxt.text, forKey: "pDesc")
newUser.setValue(titleTxt.text, forKey: "pTitle")
newUser.setValue(String(idd), forKey: "pid")
newUser.setValue(imageData, forKey: "pimg")
do {
try context.save()
let alertController = UIAlertController(title: "Alert", message: "Added!", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
// Code in this block will trigger when OK button tapped.
self.clearContent()
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "DetailsViewControllerID") as! DetailsViewController
self.navigationController?.pushViewController(nextViewController, animated: true)
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion:nil)
} catch {
print("Failed saving")
}
}
func clearContent(){
self.descTxt.text = ""
self.titleTxt.text = ""
self.imgVw.image = UIImage(named: "profImage")
}
@IBAction func CamClk(_ sender: Any) {
CameraHandler.shared.showActionSheet(vc: self)
CameraHandler.shared.imagePickedBlock = { (image) in
self.imgVw.image = image
}
}
@IBAction func NxtVw(_ sender: Any) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "DetailsViewControllerID") as! DetailsViewController
self.navigationController?.pushViewController(nextViewController, animated: true)
}
}
extension Date {
var ticks: UInt64 {
return UInt64((self.timeIntervalSince1970 + 62_135_596_800) * 10_000_000)
}
}
DetailsViewController.swift
import UIKit
import CoreData
class DetailsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var result: [NSManagedObject] = []
@IBOutlet weak var tblList: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.fetchData()
self.tblList.reloadData()
// Do any additional setup after loading the view.
}
func fetchData() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Product")
do {
result = try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
// MARk: - tableViewDelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return result.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let record = result[indexPath.row]
let cell:listData = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath as IndexPath) as! listData
cell.lblTitle.text = record.value(forKeyPath: "pTitle") as? String
let formatter = DateFormatter()
formatter.dateFormat = "dd-MMM-yyyy"
let myString = formatter.string(from: record.value(forKeyPath: "pDate") as! Date)
cell.lblDate.text = myString
cell.lblDesc.text = record.value(forKeyPath: "pDesc") as? String
cell.imgPro.image = UIImage(data: (record.value(forKey:"pimg") as! Data), scale: 1.0)
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let record = result[indexPath.row]
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Product")
request.predicate = NSPredicate(format: "pid = %@", (record.value(forKeyPath: "pid") as? String)!)
request.returnsObjectsAsFaults = false
do {
let objects = try context.fetch(request)
for object in objects {
context.delete(object as! NSManagedObject)
}
try context.save()
} catch _ {
// error handling
}
fetchData()
tblList.reloadData()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
class listData: UITableViewCell {
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblDate: UILabel!
@IBOutlet weak var lblDesc: UILabel!
@IBOutlet weak var imgPro: UIImageView!
}
CameraHandler.swift
import UIKit
import Foundation
class CameraHandler: NSObject {
static let shared = CameraHandler()
fileprivate var currentVC: UIViewController!
//MARK: Internal Properties
var imagePickedBlock: ((UIImage) -> Void)?
func camera()
{
if UIImagePickerController.isSourceTypeAvailable(.camera){
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.allowsEditing = true
myPickerController.sourceType = .camera
currentVC.present(myPickerController, animated: true, completion: nil)
}
}
func photoLibrary()
{
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.allowsEditing = true
myPickerController.sourceType = .photoLibrary
currentVC.present(myPickerController, animated: true, completion: nil)
}
}
func showActionSheet(vc: UIViewController) {
currentVC = vc
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (alert:UIAlertAction!) -> Void in
self.camera()
}))
actionSheet.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { (alert:UIAlertAction!) -> Void in
self.photoLibrary()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
vc.present(actionSheet, animated: true, completion: nil)
}
}
extension CameraHandler: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
currentVC.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
self.imagePickedBlock?(image)
}else{
print("Something went wrong")
}
currentVC.dismiss(animated: true, completion: nil)
}
}
AppDelegate.swift
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "CoreData_Sample")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
OutPut
Upvotes: 1
Reputation: 13600
Approach 1
// Create an Dictionary with all the Info and store a dictionary into UserDefault rather individual values.
let info: [String: Any] = ["Age" : 25,
"UseTouchID" : true,
"SavedArray" : ["Value 1", "Value 2", "Value 3"],
"SavedDict" : ["Name": "Paul", "Country": "UK"]]
let userDefaults = UserDefaults.standard
// Write dictionary to UserDefaults
userDefaults.set(info, forKey: "info")
// Its not mendatory to invoke 'synchronize' function as system automatically persists into Userdefault.
userDefaults.synchronize()
// Read dictionary from UserDefaults
if let readInfo: [String: Any] = userDefaults.value(forKey: "info") as? [String : Any] {
print(readInfo)
} else {
print("failed to read from UserDefaults.")
}
Approach 2
// Create a Class named "Info" with all properties.
class Info: NSCoding {
var age: Int
var useTouchID: Bool
var savedArray: [String]
var savedDict: [String : Any]
init(age: Int, useTouchId: Bool, arrayInfo: [String], dict: [String: Any]) {
self.age = age
self.useTouchID = useTouchId
self.savedArray = arrayInfo
self.savedDict = dict
}
required convenience init?(coder decoder: NSCoder) {
guard let age = decoder.decodeObject(forKey: "age") as? Int,
let useTouchID = decoder.decodeObject(forKey: "useTouchID") as? Bool, let infoArray = decoder.decodeObject(forKey: "savedArray") as? [String], let infoDict = decoder.decodeObject(forKey: "savedDict") as? [String: Any]
else { return nil }
self.init(age: age, useTouchId: useTouchID, arrayInfo: infoArray, dict: infoDict)
}
func encode(with coder: NSCoder) {
coder.encode(self.age, forKey: "age")
coder.encode(self.useTouchID, forKey: "useTouchID")
coder.encode(self.savedArray, forKey: "savedArray")
coder.encode(self.savedDict, forKey: "savedDict")
}
}
// Create Instance of Info with all required details.
let objInfo = Info(age: 25, useTouchId: true, arrayInfo: ["Value 1", "Value 2", "Value 3"], dict: ["Name": "Paul", "Country": "UK"])
let userDefaults = UserDefaults.standard
// Convert Info object to Data and save into UserDefaults.
userDefaults.set(try NSKeyedArchiver.archivedData(withRootObject: objInfo, requiringSecureCoding: false), forKey: "userInfo")
// Read userInfo from UserDefaults and convert back to Info object.
if let decodedNSData = userDefaults.object(forKey: "userInfo") as? NSData,
let userInfo = NSKeyedUnarchiver.unarchiveObject(with: decodedNSData as Data) as? Info {
print(userInfo.age, userInfo.useTouchID)
} else {
print("failed to parse.")
}
Approach 3 is to use Codable protocol introduced in swift 4, which eliminate need to NSCoder class. There are many answers/samples around internet.
Upvotes: 0
Reputation: 298
For Swift 4.2
To Save
let defaults = UserDefaults.standard
//savings
defaults.set(25, forKey: "Age")
// To save Boolean
defaults.set(true, forKey: "UseTouchID")
// To save Float
defaults.set(CGFloat.pi, forKey: "Pi")
//To save array
let array = ["Hello", "World"]
defaults.set(array, forKey: "SavedArray")
// To save Dictionary
let dict = ["Name": "Paul", "Country": "UK"]
defaults.set(dict, forKey: "SavedDict")
defaults.synchronize()
To Retrieve
let defaults = UserDefaults.standard
// Returns the object associated with the specified key.
let ageStr = defaults.value(forKey: "Age")
let userTocuhId = defaults.object(forKey: "UseTouchID")
let saveArray = defaults. array (forKey:"SavedArray")
let dictionary = defaults. dictionary (forKey:"SavedDict")
For more details follow Apple document Apple document and medium Example. User defaults Example
Once you save the data in UserDefaults, you can retrieve with the specified key and populate the data in UIViewController.
Upvotes: 0
Reputation: 55
To Save:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:@"Text" forKey:@"Stringkey"];
// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:@"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];
// saving a Bool
[prefs setObject:@"YES" forKey:@"boolKey"];
[prefs synchronize];
To Retrieve
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting a NSString
NSString *myString = [prefs stringForKey:@"Stringkey"];
// getting a NSInteger
NSInteger myInt = [prefs integerForKey:@"integerKey"];
// getting a Float
float myFloat = [prefs floatForKey:@"floatKey"];
// getting a Bool
Bool isYes = [prefs floatForKey:@"boolKey"];
Upvotes: 0