swift - CoreData - ios

I have a custom NSManagedObject:
import Foundation
import CoreData
#objc(Article)
class Article: NSManagedObject {
#NSManaged var articleID: String
#NSManaged var isFavorite: Bool
init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?, articleID: String, isFavorite: Bool) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
self.articleID = articleID
self.isFavorite = isFavorite
}
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
}
But I got error when I trie to add a new entry to CoreData:
let articleEntity = NSEntityDescription.entityForName("Article", inManagedObjectContext: self.context!)
let newArticle = Article(entity: articleEntity!, insertIntoManagedObjectContext: self.context!)
newArticle.articleID = articleID
newArticle.isFavorite = true
Use of unresolved identifier 'Article'

From the information above, it looks like you have't added the class for the entity in configuration of the coredata. Make sure you have mapped class against entity in the configuration of .xcdatamodeld file. You can check the below example.

// 1) Swift File
import Foundation
import CoreData
import UIKit
class DatabaseHelper{
static var shareInstance = DatabaseHelper()
let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
func save(object:[String:String]){
let student = NSEntityDescription.insertNewObject(forEntityName: "Student", into: context!) as! Student
student.name = object["name"]
student.address = object["address"]
student.city = object["city"]
student.mobile = object["mobile"]
do{
try context?.save()
}catch{
print("Data is not save")
}
}
func getStudentData() -> [Student]{
var student = [Student]()
let fatchRequest = NSFetchRequest<NSManagedObject>(entityName: "Student")
do{
student = try context?.fetch(fatchRequest)as![Student]
}catch{
print("can not get Data")
}
return student
}
// 2) view Controller
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var txtCity: UITextField!
#IBOutlet weak var txtMobile: UITextField!
#IBOutlet weak var txtAddress: UITextField!
#IBOutlet weak var txtName: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func btnSaveData(_ sender: Any) {
var dict = ["name":txtName.text,"address":txtAddress.text,"city":txtCity.text,"mobile":txtMobile.text]
DatabaseHelper.shareInstance.save(object: dict as! [String : String])
}
#IBAction func btnShowAction(_ sender: Any) {
let show = storyboard?.instantiateViewController(withIdentifier: "AnotherViewController")as! AnotherViewController
self.navigationController?.pushViewController(show, animated: true)
}
}
// 3) Data get in table View
import UIKit
class AnotherViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
#IBOutlet weak var tblView: UITableView!
var student = [Student]()
override func viewDidLoad() {
super.viewDidLoad()
student = DatabaseHelper.shareInstance.getStudentData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return student.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tblView.dequeueReusableCell(withIdentifier: "tblCell", for: indexPath)as! tblCell
cell.lblName.text = student[indexPath.row].name
cell.lblAddress.text = student[indexPath.row].address
cell.lblCity.text = student[indexPath.row].city
cell.lblMobile.text = student[indexPath.row].mobile
return cell
}
}
class tblCell : UITableViewCell{
#IBOutlet weak var lblName: UILabel!
#IBOutlet weak var lblAddress: UILabel!
#IBOutlet weak var lblCity: UILabel!
#IBOutlet weak var lblMobile: UILabel!
}

// 4) AppViewController
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
print("Document Directory:", FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last ?? "Not found!!")
return true
}

Related

How to save data from one view controller and show in another view controller using core data

I need help with solving one problem with core data. I have a news app with two view controllers. In the main view controller I'm loading news data in table view in custom cell. Here I have a button, on which should I tap and save news to another view controller. How it looks now: How it looks So when we tap on this blue button, it should save news from the cell and display on second view controller. I have created a core data model like this: Core data model Here is code in my first view controller:
import UIKit
import SafariServices
import CoreData
class ViewController: UIViewController, UISearchBarDelegate, UpdateTableViewDelegate {
#IBOutlet weak var pecodeTableView: UITableView!
private var articles = [News]()
// private var viewModels = [NewsTableViewCellViewModel]()
private var viewModel = NewsListViewModel()
var newsTitle: String?
var newsAuthor: String?
var newsDesc: String?
var urlString: String?
var newsDate: String?
private let searchVC = UISearchController(searchResultsController: nil)
var selectedRow = Int()
override func viewDidLoad() {
super.viewDidLoad()
pecodeTableView.delegate = self
pecodeTableView.dataSource = self
pecodeTableView.register(UINib(nibName: S.CustomCell.customNewsCell, bundle: nil), forCellReuseIdentifier: S.CustomCell.customCellIdentifier)
// fetchAllNews()
viewModel.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
categoryMenu()
loadData()
}
private func loadNewsData(api: String){
let apiService = APIService(categoryCode: api)
apiService.getNewsData {(result) in
switch result{
case .success(let NewsOf):
CoreData.sharedInstance.saveDataOf(news: NewsOf.articles)
case .failure(let error):
print("Error processing json data: \(error)")
}
}
}
func reloadData(sender: NewsListViewModel) {
self.pecodeTableView.reloadData()
}
//MARK: - Networking
private func loadData(){
viewModel.retrieveDataFromCoreData()
}
//MARK: - UIView UImenu
func categoryMenu(){
var categoryAction: UIMenu{
let menuAction = Category.allCases.map { (item) -> UIAction in
let name = item.rawValue
return UIAction(title: name.capitalized, image: UIImage(systemName: item.systemImage)) { [weak self](_) in
self?.loadNewsData(api: name)
self?.loadData()
self?.reloadData(sender: self!.viewModel)
}
}
return UIMenu(title: "Change Category", children: menuAction)
}
let categoryButton = UIBarButtonItem(image: UIImage(systemName: "scroll"), menu: categoryAction)
navigationItem.leftBarButtonItem = categoryButton
}
#IBAction func goToFavouritesNews(_ sender: UIButton) {
performSegue(withIdentifier: S.Segues.goToFav, sender: self)
}
private func createSearchBar() {
navigationItem.searchController = searchVC
searchVC.searchBar.delegate = self
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfRowsInSection(section: section)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: S.CustomCell.customCellIdentifier, for: indexPath) as? CustomNewsCell
let object = viewModel.object(indexPath: indexPath)!
cell?.setCellWithValuesOf(object)
cell?.saveNewsBtn.tag = indexPath.row
cell?.saveNewsBtn.addTarget(self, action: #selector(didTapCellButton(sender:)), for: .touchUpInside)
return cell!
}
#objc func didTapCellButton(sender: FavouritesCell) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context: NSManagedObjectContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "SavedNews", in: context)
let newNewsSave = SavedNews(entity: entity!, insertInto: context)
newNewsSave.author = newsAuthor
newNewsSave.desc = newsDesc
newNewsSave.title = newsTitle
do {
try context.save()
savedNews.append(newNewsSave)
navigationController?.popViewController(animated: true)
} catch {
print("Error saving")
}
print("Done")
}
Also I want to show you my parsing functions and model for this: *APIService.swift*
import Foundation
class APIService{
private var dataTask: URLSessionDataTask?
public let resourceURL: URL
private let API_KEY = "e2a69f7f9567451ba484c85614356c30"
private let host = "https://newsapi.org"
private let headlines = "/v2/top-headlines?"
init(categoryCode: String){
let resourceString = "\(host)\(headlines)country=us&category=\(categoryCode)&apiKey=\(API_KEY)"
print(resourceString)
guard let resourceURL = URL(string: resourceString) else {
fatalError()
}
self.resourceURL = resourceURL
}
//MARK: - Get News
func getNewsData(completion: #escaping (Result<Articles, Error>) -> Void){
dataTask = URLSession.shared.dataTask(with: resourceURL) { (data, response, error) in
if let error = error{
completion(.failure(error))
print("DataTask error: - \(error.localizedDescription)")
}
guard let response = response as? HTTPURLResponse else{
print("Empty Response")
return
}
print("Response status code: - \(response.statusCode)")
guard let data = data else {
print("Empty Data")
return
}
do{
let decoder = JSONDecoder()
let jsonData = try decoder.decode(Articles.self, from: data)
DispatchQueue.main.async {
completion(.success(jsonData))
}
}catch let error{
completion(.failure(error))
}
}
dataTask?.resume()
}
}
And here is NewsModel.swift:
import Foundation
struct Articles: Codable {
let articles: [News]
private enum CodingKeys: String, CodingKey{
case articles = "articles"
}
}
struct News: Codable {
let author: String?
let source: Source
let title: String
let description: String?
let url: URL?
let urlToImage: URL?
let publishedAt: String?
private enum CodingKeys: String, CodingKey{
case author = "author"
case title = "title"
case url = "url"
case urlToImage = "urlToImage"
case publishedAt = "publishedAt"
case description = "description"
case source = "source"
}
}
struct Source: Codable {
let name: String?
}
Here is my code in CustomNewsCell.swift:
import UIKit
protocol CustomNewsDelegate: AnyObject {
func btnFavPress(cell: CustomNewsCell)
}
private var loadImage = LoadToImage()
private var formatDate = FormatDate()
class CustomNewsCell: UITableViewCell {
weak var delegate: CustomNewsDelegate?
#IBOutlet weak var saveNewsBtn: UIButton!
#IBOutlet weak var imageOutlet: UIImageView!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var descLabel: UILabel!
#IBOutlet weak var authorLabel: UILabel!
#IBOutlet weak var dateLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setCellWithValuesOf(_ news: SavedNews){
updateUI(title: news.title, url: news.url, urlToImage: news.urlToImage, publishedAt: news.publishedAt, author: news.author ?? "No author", description: news.desc, source: news.source)
}
private func updateUI(title: String?, url: URL?, urlToImage: URL?, publishedAt: String?, author: String, description: String?, source: String?){
//title
self.titleLabel.text = title
self.authorLabel.text = author
self.descLabel.text = description
//date
let dateString = formatDate.formatDate(from: publishedAt ?? "")
let date = formatDate.formatDateString(from: dateString)
self.dateLabel.text = date
//image
guard let urlToImageString = urlToImage else {return}
imageOutlet.image = nil
loadImage.getImageDataFrom(url: urlToImageString) { [weak self] data in
guard let data = data, let image = UIImage(data: data) else{
DispatchQueue.main.async {
self?.imageOutlet.image = UIImage(named: "noImage")
}
return
}
self?.imageOutlet.image = image
}
}
#IBAction func saveBtnPressed(_ sender: UIButton) {
delegate?.btnFavPress(cell: self)
}
}
First time I've tried with delegate method for this blue button, but now as you can see I've created a selector method. Maybe it's not correct and need to fix it. Here is the code in the second view controller, which should show saved news from first view controller:
import UIKit
import CoreData
var savedNews = [SavedNews]()
class FavouriteNewsViewController: UIViewController {
#IBOutlet weak var favTableView: UITableView!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var result: [SavedNews] = []
var newsTitleNew: String?
var newsDescNew: String?
var newsAuthor: String?
override func viewDidLoad() {
super.viewDidLoad()
favTableView.delegate = self
favTableView.delegate = self
fetch()
// loadSavedNews()
favTableView.register(UINib(nibName: S.FavouriteCell.favouriteCell, bundle: nil), forCellReuseIdentifier: S.FavouriteCell.favouriteCellIdentifier)
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
// fetch()
favTableView.reloadData()
}
#IBAction func goToNewsFeed(_ sender: UIButton) {
performSegue(withIdentifier: S.Segues.goToNewsFeed, sender: self)
}
}
extension FavouriteNewsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return savedNews.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 140
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = favTableView.dequeueReusableCell(withIdentifier: S.FavouriteCell.favouriteCellIdentifier, for: indexPath) as! FavouritesCell
let newRslt: SavedNews!
newRslt = savedNews[indexPath.row]
cell.favAuthor.text = newRslt.author
cell.favDesc.text = newRslt.desc
cell.favTitle.text = newRslt.title
return cell
}
func fetch() {
let request = NSFetchRequest<SavedNews>(entityName: "SavedNews")
do {
savedNews = try context.fetch(request)
} catch {
print(error)
}
}
}
And code for cell for this controller:
import UIKit
import CoreData
class FavouritesCell: UITableViewCell {
#IBOutlet weak var favImage: UIImageView!
#IBOutlet weak var favTitle: UILabel!
#IBOutlet weak var favDesc: UILabel!
#IBOutlet weak var favAuthor: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
If somebody can help with this, it will be amazing. Because I really don't how to do this. Thank you!

How to save existing singleton table view data in core data?

I have singleton shopping cart in my project like this var fromSharedFood = SingletonCart.sharedFood.food. I am getting all food data from MainVC to DetailVC -> MyCartVC. I have table view in MainVC. I want to save MainVC table view datas to CoreData.
My project was offline. Now, it communicates with web api. I used Singleton for data transition from MainVC to DetailVC to MyCartVC. Now, if user logged in the system I need to save him/her Cart with core data or etc.
i.e. User add a food to cart and log out him/her Cart must be saved when re-login.
I tried with UserDefaults self.myCartUserDefaults.set(myCartTableView.dataSource, forKey: "userCart") but it is not make sense.
I created CoreData entities for food name and price.
Here is MyCartVC
import UIKit
import CoreData
class MyCartViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var fromDetailFoodNames = ""
var fromDetailFoodPrices = ""
var backgroundView: UIView?
#IBOutlet weak var myCartTableView: UITableView!
#IBOutlet weak var totalPriceLabel: UILabel!
private let persistentContainer = NSPersistentContainer(name: "MyCartData")
var food: Food?
var fromSharedFood = SingletonCart.sharedFood.food
//TODO: - Approve my cart
#IBAction func approveCart(_ sender: Any) {
}
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.tabBar.isHidden = false
myCartTableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
self.myCartTableView.reloadData()
if foodCoreData.count == 0 {
myCartTableView.setEmptyView(title: "Sepetinizde ürün bulunmamaktadır", message: "Seçtiğiniz yemekler burada listelenir.")
}
else {
myCartTableView.restore()
self.tabBarController?.viewControllers![1].tabBarItem.badgeValue = "\(foodCoreData.count)"
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext =
appDelegate.persistentContainer.viewContext
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "MyCartData")
do {
foodCoreData = try managedContext.fetch(fetchRequest)
print("COREDATA FETCH EDİLDİ")
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if fromSharedFood.count != 0 {
tableView.restore()
}
return fromSharedFood.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let foodName = fromSharedFood[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "myCartCell", for: indexPath) as! MyCartTableViewCell
cell.myCartFoodNameLabel.text = foodName.ProductTitle
self.tabBarController?.viewControllers![1].tabBarItem.badgeValue = "\(fromSharedFood.count)"
cell.myCartFoodPriceLabel.text = foodName.PriceString
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
fromSharedFood.remove(at: indexPath.row)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .automatic)
if fromSharedFood.count == 0 {
myCartTableView.reloadData()
self.tabBarController?.viewControllers![1].tabBarItem.badgeValue = nil }
else {
self.tabBarController?.viewControllers![1].tabBarItem.badgeValue = "\(fromSharedFood.count)"
}
myCartTableView.restore()
}
tableView.endUpdates()
}
}
}
EDIT:
My data come from DetailVC with addBasket() button. First of all, I tried save DetailVC label datas to core data. After that fetched from MyCartVC but did not get any response.
Here is DetailVC:
import UIKit
import CoreData
class DetailViewController: UIViewController, TagListViewDelegate {
#IBOutlet weak var foodTitle: UILabel!
#IBOutlet weak var foodSubTitle: UILabel!
#IBOutlet weak var foodPrice: UILabel!
#IBOutlet weak var foodQuantity: UILabel!
#IBOutlet weak var detailFoodImage: UIImageView!
#IBOutlet weak var tagListView: TagListView!
var window: UIWindow?
var detailFoodName = ""
var detailFoodPrice = ""
var detailPhotoData = String()
var searchFoods: String!
var priceFood: Double!
var foodCoreData: [NSManagedObject] = []
var food: Food?
override func viewDidLoad() {
super.viewDidLoad()
foodQuantity.text = "1"
foodTitle.text = food?.ProductTitle ?? ""
foodPrice.text = food?.PriceString
foodSubTitle.text = food?.Description
tagListView.delegate = self
setupIngredientsTag()
self.tabBarController?.tabBar.isHidden = true
self.navigationController?.navigationItem.title = "Sipariş Detayı"
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "FoodOrder")
self.window?.rootViewController = viewController
}
func save(foodName: String, foodPrice: String) {
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext =
appDelegate.persistentContainer.viewContext
let entity =
NSEntityDescription.entity(forEntityName: "MyCartData",
in: managedContext)!
let foods = NSManagedObject(entity: entity,
insertInto: managedContext)
foods.setValue(foodName, forKeyPath: "fromDetailFoodNames")
foods.setValue(foodPrice, forKeyPath: "fromDetailFoodPrices")
do {
try managedContext.save()
foodCoreData.append(foods)
print("COREDATA KAYDEDİLDİ!")
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
//TODO:- Add to basket
#IBAction func addBasket(_ sender: Any) {
SingletonCart.sharedFood.food.append(food!)
self.performSegue(withIdentifier: "toMyCart", sender: nil)
self.navigationController?.navigationBar.isHidden = false
self.tabBarController?.tabBar.isHidden = false
self.isLoading(true)
guard let nameToSave = foodTitle.text else { return }
guard let priceToSave = foodPrice.text else { return }
self.save(foodName: nameToSave, foodPrice: priceToSave)
}
#IBAction func cancelButtonClicked(_ sender: UIBarButtonItem) {
self.navigationController?.popViewController(animated: true)
}
#IBAction func favoriteButtonClicked(_ sender: UIBarButtonItem) {
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.navigationBar.isHidden = false
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.navigationBar.isHidden = true
}
}
SingletonCart
import Foundation
import UIKit
class SingletonCart {
static let sharedFood = SingletonCart()
var food: [Food] = []
private init() {}
}
Expected output is when user logout save him/her shopping cart.
You've got a couple of concepts wrong from what I see. Core Data Programming Guide will help you a lot to get how it works and how to save data.
For your table listings you should use an NSFetchedResultsController instead of managing a collection yourself.
Then when adding a new model from a detail View Controller you should create a new background context, create the entity, set its values and then save it.
appDelegate.persistentContainer.performBackgroundTask { (context) in
let entity =
NSEntityDescription.entity(forEntityName: "MyCartData",
in: managedContext)!
let foods = NSManagedObject(entity: entity,
insertInto: managedContext)
foods.setValue(foodName, forKeyPath: "fromDetailFoodNames")
foods.setValue(foodPrice, forKeyPath: "fromDetailFoodPrices")
_ = try? managedContext.save()
}
This will save this object to the persistent store, them refresh your view context and your NSFetchedResultsController will update your tableView controller automatically

How can I passing data UIViewContoller from UIView in swift3

How can i passing data uiviewController from uiview
I am Using function but it was not working
protocol name is startcalldelegate and function name is startcall
UIView Code
protocol StartCallDelegate: class {
func startCall(localNickname :String, remoteNickname :String)}
class CardView: UIView {
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
weak var delegate: CardViewDelegate?
weak var socketdelegate: StartCallDelegate?
#IBOutlet weak var UserPhoto: UIImageView!
#IBOutlet weak var UserNickName: UILabel!
#IBOutlet weak var UserAge: UILabel!
#IBOutlet weak var UserPeople: UILabel!
var localNickname: String = ""
var remoteNickname: String = ""
#IBAction func SendMessage(_ sender: Any) {
print("SendMessage")
//print(localNickName)
//print(UserNickName.text!)
}
#IBAction func SendVideoCall(_ sender: Any) {
print("SendVideoCall")
let entityDescription = NSEntityDescription.entity(forEntityName: "Profile", in: managedObjectContext)
let request = NSFetchRequest<NSFetchRequestResult>()
request.entity = entityDescription
do {
let objects = try managedObjectContext.fetch(request)
if objects.count > 0 {
let match = objects[0] as! NSManagedObject
localNickname = match.value(forKey: "nick") as! String
} else {
print("Nothing founded")
}
} catch {
print("error")
}
remoteNickname = UserNickName.text!
socketdelegate?.startCall(localNickname: localNickname, remoteNickname: remoteNickname)
delegate?.VideoChatSegue()
}
}
UIViewcontroller Code
class ViewController: UIViewcontroller, StartCallDelegate {
var localNickname: String = ""
var remoteNickname: String = ""
override func viewDidLoad() {
super.viewDidLoad()
print(localNickname)
print(remoteNickname)
}
func startCall(localNickname: String, remoteNickname: String) {
print("Action startcall func")
self.localNickname = localNickname
self.remoteNickname = remoteNickname
}
startCall func not working
You need to define delegate in viewcontroller' ViewDidLoad
let objOardView = CardView() // this is only test purpose
objOardView.socketdelegate = self

Passing data from text field to Firebase

I am getting error in ToDoViewController.Swift here is the overall code:
I am makeing a simple app for taking orders from customers. and orders will store in Firebase.
View Controller.Swift
import UIKit
import Firebase
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var todoList = [Todo]()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadData()
}
func loadData() {
self.todoList.removeAll()
let ref = FIRDatabase.database().reference()
ref.child("todoList").observeSingleEvent(of: .value, with: { (snapshot) in
if let todoDict = snapshot.value as? [String:AnyObject] {
for (_,todoElement) in todoDict {
print(todoElement);
let todo = Todo()
todo.name = todoElement["name"] as? String
todo.message = todoElement["message"] as? String
todo.reminderDate = todoElement["date"] as? String
self.todoList.append(todo)
}
}
self.tableView.reloadData()
}) { (error) in
print(error.localizedDescription)
}
}
//MARK: TableView datasource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.todoList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoCell")
cell!.textLabel?.text = todoList[indexPath.row].name
return cell!
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
ToDoViewController
import UIKit
import Firebase
class ToDoViewController: UIViewController {
var todo:Todo?
#IBOutlet weak var nameField: UITextField!
#IBOutlet weak var messageField: UITextField!
#IBOutlet weak var dateFormatter: UIDatePicker!
#IBAction func Done(_ sender: Any) {
if todo == nil {
todo = Todo()
}
// first section
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm"
todo?.name = self.nameField.text
todo?.message = self.messageField.text
todo?.reminderDate = dateFormatter.string(from: self.dateFormatter.date)
//second section
let ref = FIRDatabase.database().reference()
let key = ref.child("todoList").childByAutoId().key
let dictionaryTodo = [ "name" : todo!.name! ,
"message" : todo!.message!,
"date" : todo!.reminderDate!]
let childUpdates = ["/todoList/\(key)": dictionaryTodo]
ref.updateChildValues(childUpdates, withCompletionBlock: { (error, ref) -> Void in
self.navigationController?.popViewController(animated: true)
})
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let todoVC = self.storyboard!.instantiateViewController(withIdentifier: "ToDoVC") as! ToDoViewController
todoVC.todo = todoList[indexPath.row]
self.navigationController?.pushViewController(todoVC, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if self.todo != nil {
nameField.text = self.todo?.name
messageField.text = self.todo?.message
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm"
let date = dateFormatter.date(from: self.todo!.reminderDate!)
datePicker.date = date!
}
}
}
Todo.Swift
import UIKit
class Todo: NSObject {
var name :String?
var message: String?
var reminderDate: String?
// id which is set from firebase to uniquely identify it
var uniqueId:String?
}
Something is wrong with your code:
Use of un-resolved identifier 'todoList':
todoList is declared in View Controller.Swift and you cannot use it in ToDoViewController.
Cannot assign to property: 'date' is a method:
In the code datePicker is undefined and #IBOutlet weak var dateFormatter: UIDatePicker! should be:
#IBOutlet weak var datePicker: UIDatePicker!
AND In the image dateFormatter.date = date! should be:
datePicker.date = date!

I would like to display selected search results from core data in a table view using swift

I have spent a lot of time researching this problem and have not found any help relevant to the matter, so I am hoping this is not a fool's errand. I am developing an app with a core data model where I want the user to perform a search in one screen of the core data, and be able to select which records from the search result are stored in the table view. Every tutorial I have found assumes that I want every record in core data automatically displayed in the table view. At this point I believe I have all of the core data code, and much of the table view code implemented as I would desire. The only thing I want to change is allowing the user to search the core data, and choose which records to display in the table view. The first code snippet I have below is of the table view controller I have to display the core data, and the code following that is the code for the view controller I am using to save, find, and eventually select core data to be displayed. Thank you in advance for your help.
`import Foundation
import UIKit
import CoreData
class PatientViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController()
func getFetchedResultController() -> NSFetchedResultsController {
fetchedResultController = NSFetchedResultsController(fetchRequest: taskFetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultController
}
func taskFetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: "Patients")
let sortDescriptor = NSSortDescriptor(key: "lastname", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
return fetchRequest
}
var patients = [Patients]()
override func viewDidLoad() {
super.viewDidLoad()
fetchedResultController = getFetchedResultController()
fetchedResultController.delegate = self
fetchedResultController.performFetch(nil)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
let numberOfSections = fetchedResultController.sections?.count
return numberOfSections!
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRowsInSection = fetchedResultController.sections?[section].numberOfObjects
return numberOfRowsInSection!
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("MyCellTwo", forIndexPath: indexPath) as! UITableViewCell
let patient = fetchedResultController.objectAtIndexPath(indexPath) as! Patients
cell.textLabel?.text = patient.lastname + ", " + patient.firstname
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let managedObject:NSManagedObject = fetchedResultController.objectAtIndexPath(indexPath) as! NSManagedObject
managedObjectContext?.deleteObject(managedObject)
managedObjectContext?.save(nil)
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.reloadData()
}
}`
And the second bit of code.
import UIKit
import CoreData
class AddPatientViewController: UIViewController {
#IBOutlet weak var socialSecurityNumber: UITextField!
#IBOutlet weak var lastName: UITextField!
#IBOutlet weak var firstName: UITextField!
#IBOutlet weak var middleInitial: UITextField!
#IBOutlet weak var streetAddress: UITextField!
#IBOutlet weak var apartment: UITextField!
#IBOutlet weak var city: UITextField!
#IBOutlet weak var state: UITextField!
#IBOutlet weak var zipCode: UITextField!
#IBOutlet weak var homePhone: UITextField!
#IBOutlet weak var cellPhone: UITextField!
#IBOutlet weak var workPhone: UITextField!
#IBOutlet weak var mrn: UILabel!
#IBOutlet weak var primaryDiagnosis: UITextField!
#IBAction func savePatient(sender: AnyObject) {
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var newPatient = NSEntityDescription.insertNewObjectForEntityForName("Patients", inManagedObjectContext: context) as! NSManagedObject
newPatient.setValue(firstName.text, forKey: "firstname")
newPatient.setValue(lastName.text, forKey: "lastname")
newPatient.setValue(socialSecurityNumber.text, forKey: "ssn")
newPatient.setValue(cellPhone, forKey: "cellphone")
/*newPatient.setValue(middleInitial.text, forKey: "middileinitial")
newPatient.setValue(streetAddress, forKey: "streetaddress")
newPatient.setValue(apartment, forKey: "apartment")
newPatient.setValue(city, forKey: "city")
newPatient.setValue(state, forKey: "state")
newPatient.setValue(zipCode, forKey: "zipcode")
newPatient.setValue(homePhone, forKey: "homephone")
newPatient.setValue(workPhone, forKey: "workphone")
newPatient.setValue(primaryDiagnosis, forKey: "primarydiagnosis")*/
context.save(nil)
println(newPatient)
println("Object Saved.")
}
#IBAction func findPatient(sender: AnyObject) {
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Patients")
request.returnsObjectsAsFaults = false;
request.predicate = NSPredicate(format: "lastname = %#", lastName.text)
var results:NSArray = context.executeFetchRequest(request, error: nil)!
if(results.count > 0) {
var res = results[0] as! NSManagedObject
lastName.text = res.valueForKey("lastname") as! String
firstName.text = res.valueForKey("firstname") as! String
socialSecurityNumber.text = res.valueForKey("ssn") as! String
//for res in results{
// println(res)
//}
} else {
println("0 Results Returned...Potential Error")
}
}
#IBAction func selectPatient(sender: AnyObject) {
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

Resources