gpt4 book ai didi

ios - 想将数据保存在 nsuserdefault 中并将其传输到另一个 Controller 的 TableView 中

转载 作者:行者123 更新时间:2023-11-29 11:28:48 31 4
gpt4 key购买 nike

我有一个 detailviewcontroller 文件,其中有一个 ImageView 、一个文本字段、一个 TextView 和一个日期选择器。 ImageView 图像让我从第一个 Controller 。当我填写文本字段、 TextView 、选择日期等剩余数据时,然后当我单击导航栏中的保存按钮时,数据应保存在 nsuserdefault 中并传递到另一个 Controller 的 TableView 。当我再次启动应用程序并再次填写详细信息时,该数据和以前的数据也应该在那里。不知道该怎么做

我的 Storyboard: storyboard file

我的 detailviewcontroller 文件:

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
// }
// }

}

我的 listtableviewcontroller 文件:

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
}

最佳答案

使用核心数据

enter image description here

enter image description here

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)")
}
}
}

}

输出

enter image description here enter image description here

关于ios - 想将数据保存在 nsuserdefault 中并将其传输到另一个 Controller 的 TableView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55790400/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com