Xcode App crashing with no debug information in console - ios

I am using Xcode and for some reason my app is crashing without showing any debug information in the console. It prints code until "distance: (distance)", but after that there is nothing. I am not sure what to fix as there is nothing there to help me in the console. Here is my code:
//
// TableViewController.swift
// grosseries
//
// Created by Amish Tyagi on 5/29/20.
// Copyright © 2020 grosseries. All rights reserved.
//
import UIKit
import Firebase
import FirebaseFirestore
import FirebaseAuth
import FirebaseCore
import FirebaseDatabase
import CoreLocation
import MapKit
class TableViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet var tableView: UITableView!
var ref : DatabaseReference! = Database.database().reference()
var volunteer : Bool = false
let locationManager = CLLocationManager()
var destinationCord = CLLocationCoordinate2D()
#IBOutlet weak var addItemButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
let defaults = UserDefaults.standard
Constants.Storyboard.food = defaults.object(forKey: "foodArray") as? [String] ?? [String]()
print(Constants.Storyboard.food)
// Do any additional setup after loading the view.
let db = Firestore.firestore()
let userID = Auth.auth().currentUser?.uid
let usersRef = ref.child("Users")
let thisUserRef = usersRef.child(userID!)
let docRef = db.collection("Users").document(userID!)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
let userData = document.data()!["userType"]
if (userData as? String == "Volunteer") {
self.volunteer = true
self.addItemButton.isEnabled = false
self.addItemButton.alpha = 0
print("hi!")
}
} else {
print("Document does not exist")
}
}
// Force the SDK to fetch the document from the cache. Could also specify
// FirestoreSource.server or FirestoreSource.default.
docRef.getDocument(source: .cache) { (document, error) in
if let document = document {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Cached document data: \(dataDescription)")
} else {
print("Document does not exist in cache")
}
}
thisUserRef.observe(.value) { (snapshot) in
let value = snapshot.value as? NSDictionary
let username = value?["firstName"] as? String ?? ""
print(value)
print("username: " + username)
// let user = User(username: username)
// if (user == "Volunteer") {
// self.volunteer = true
// }
}
// ref.observeSingleEvent(of: .value, with: { snapshot in
//
// if !snapshot.exists() { return }
//
// //print(snapshot)
// let value = snapshot.value as? NSDictionary
// if let userName = value?["userType"] as? String ?? "" {
// print(userName)
// }
// if let email = snapshot.value["email"] as? String {
// print(email)
// }
//
// // can also use
// // snapshot.childSnapshotForPath("full_name").value as! String
// })
}
override func viewWillAppear(_ animated: Bool) {
tableView.reloadData()
}
#IBAction func addItemTapped(_ sender: Any) {
transitionToNext()
}
func transitionToNext() {
let nextViewController = storyboard?.instantiateViewController(identifier: "AddFoodViewController") as? AddFoodViewController
view.window?.rootViewController = nextViewController
view.window?.makeKeyAndVisible()
}
func transitionToInfo() {
let infoViewController = storyboard?.instantiateViewController(identifier: "InfoViewController") as? InformationViewController
view.window?.rootViewController = infoViewController
view.window?.makeKeyAndVisible()
}
func getAddress(address: String) {
let geoCoder = CLGeocoder()
// var distance = 0.0
geoCoder.geocodeAddressString(address) { (placemarks, error) in
guard let placemarks = placemarks, let location = placemarks.first?.location
else{
print("No Location Found")
let alert = UIAlertController(title: "No Location Found, Please enter an valid address or location", message: "", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
// self.textFieldForAddress.text = ""
self.present(alert, animated: true)
return
}
// self.tableView(tableView, cellForRowAt: tableView.indexPath(for: "cell"))
self.destinationCord = location.coordinate
}
// if (distance <= 8046) {
// return true
// }
// else {
// return false
// }
}
}
extension TableViewController : UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// This part is for later make sure to come back to it
if (volunteer == true) {
transitionToInfo()
}
else {
let alertController = UIAlertController(title: "Sorry, you are not a volunteer", message: "Since you are not a volunteer, you cannot deliver groceries to anybody else. To do this, create another account.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
}
extension TableViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("insideNumberOfRows")
return Constants.Storyboard.addressHardCode.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("begin..........")
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var count = 0
for address in Constants.Storyboard.addressHardCode {
DispatchQueue.main.sync {
getAddress(address: address)
}
// print(location.coordinate)
print("destinationCord: \(self.destinationCord)")
let sourceLocation = (self.locationManager.location?.coordinate)!
let coord1 = CLLocation(latitude: sourceLocation.latitude, longitude: sourceLocation.longitude)
let coord2 = CLLocation(latitude: self.destinationCord.latitude, longitude: self.destinationCord.longitude)
var distance = coord1.distance(from: coord2)
print("distance \(distance)")
if (distance<8046) {
print("count: \(count)")
cell.textLabel?.text = Constants.Storyboard.namesHardCode[count]
}
count+=1
}
return cell
}
}
Here is a picture of my console:
Any help would be greatly appreciated!

Related

How to get the Document ID in Firebase Database

I have a table view and when I swipe and delete the table view cell I need the data in Firebase to delete as well for that to be possible I need to have the document ID how can I get that so I can delete the table view cell and the data in Firebase?
this is the first view controller
import UIKit
import FirebaseDatabase
import Firebase
import Firestore
class TableViewController: UITableViewController {
var db:Firestore!
var employeeArray = [employee]()
var employeeKey:String = ""
override func viewDidLoad() {
super.viewDidLoad()
db = Firestore.firestore()
loadData()
checkForUpdates()
}
func loadData() {
db.collection("employee").getDocuments() {
querySnapshot, error in
if let error = error {
print("\(error.localizedDescription)")
}else{
self.employeeArray = querySnapshot!.documents.compactMap({employee(dictionary: $0.data())})
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
func checkForUpdates() {
db.collection("employee").whereField("timeStamp", isGreaterThan: Date())
.addSnapshotListener {
querySnapshot, error in
guard let snapshots = querySnapshot else {return}
snapshots.documentChanges.forEach {
diff in
if diff.type == .added {
self.employeeArray.append(employee(dictionary: diff.document.data())!)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
}
func UID() {
// let postRef = Firestore.firestore().collection("employee")
// postRef.getDocuments { (snapshot, error) in
// if error != nil {
// print("error")
//
// } else {
// if let snapshot = snapshot {
// for document in snapshot.documents {
// let data = document.data()
// self.employeeKey = document.documentID
// let newSource = employee(timeStamp: Date(), documentID: document.documentID)
// self.employeeArray.append(newSource)
// print(document.documentID)
// }
// self.tableView.reloadData()
// }
// }
// }
self.db.collection("employee").getDocuments() { (snapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in snapshot!.documents {
if document == document {
print(document.documentID)
}
}
}
}
}
#IBAction func addEmployee(_ sender: Any) {
let composeAlert = UIAlertController(title: "Add Employee", message: "Add Employee", preferredStyle: .alert)
composeAlert.addTextField { (textField:UITextField) in
textField.placeholder = "Name"
}
composeAlert.addTextField { (textField:UITextField) in
textField.placeholder = "Adress"
}
composeAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
composeAlert.addAction(UIAlertAction(title: "Add Employee", style: .default, handler: { (action:UIAlertAction) in
let documentID = ""
if let name = composeAlert.textFields?.first?.text,
let adress = composeAlert.textFields?.last?.text {
let newEmployee = employee(name: name, adress: adress,timeStamp: Date(), documentID: documentID)
var ref:DocumentReference? = nil
ref = self.db.collection("employee").addDocument(data: newEmployee.dictionary) {
error in
if let error = error {
print("Error adding document: \(error.localizedDescription)")
}else{
print("Document added with ID: \(ref!.documentID)")
}
}
}
}))
self.present(composeAlert, animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return employeeArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let tweet1 = employeeArray[indexPath.row]
cell.textLabel?.text = "\(tweet1.name) \(tweet1.adress)"
cell .detailTextLabel?.text = "\(tweet1.timeStamp) "
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) async {
print(UID())
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == UITableViewCell.EditingStyle.delete) {
db.collection("employee").document("UID").delete() { [self] err in
if let err = err {
print("Error removing document: \(err)")
} else {
print("succses")
}
}
}
}
}
`
This is the next view Controller
import UIKit
import FirebaseDatabase
import Firebase
import Firestore
protocol DocumentSeriziable {
init?(dictionary:[String:Any])
}
struct employee {
var name: String!
var adress: String!
var timeStamp: Date
var documentID: String!
var dictionary:[String : Any] {
return[
"name":name!,
"adress":adress!,
"timeStamp":timeStamp,
"documentID": documentID!,
]
}
}
extension employee : DocumentSeriziable {
init?(dictionary: [String : Any]) {
guard let name = dictionary["name"] as? String,
let adress = dictionary["adress"] as? String,
let documentID = dictionary["documentID"] as? String,
let timeStamp = dictionary["timeStamp"] as? Date else {return nil}
self.init(name: name, adress: adress, timeStamp: timeStamp, documentID: documentID)
}
}
I tried making a var documentID and trying to get the document id but I never figured out how.
You can get document documentID while you parsing the data
self.employeeArray = querySnapshot!.documents.compactMap({employee(id: $0.documentID, dictionary: $0.data())})
documentID is not a part of the data() but it uses as a key in database.
protocol DocumentSeriziable {
init?(id: String, dictionary:[String:Any])
}
extension employee : DocumentSeriziable {
init?(id: String, dictionary: [String : Any]) {
guard let name = dictionary["name"] as? String,
let adress = dictionary["adress"] as? String,
let timeStamp = dictionary["timeStamp"] as? Date else {return nil}
self.init(name: name, adress: adress, timeStamp: timeStamp, documentID: id)
}
}

Index related error in retrieving the data from Firestore database

I am not able to load the documents in chat application in Swift IOS using Firestore database, though able to successfully retrieve the data from the Firestore database, I have added the deinit method as well please assist further to resolve the error, I have added the complete view controller , please help me
Error
'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (47) must be equal to the number of rows contained in that section before the update (23), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
Code
let kBannerAdUnitID = "ca-app-pub-3940256099942544/2934735716"
#objc(FCViewController)
class FCViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,
UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// Instance variables
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var sendButton: UIButton!
var ref : CollectionReference!
var ref2: DocumentReference!
var messages: [DocumentSnapshot]! = []
var msglength: NSNumber = 10
fileprivate var _refHandle: CollectionReference!
var storageRef: StorageReference!
var remoteConfig: RemoteConfig!
private let db = Firestore.firestore()
private var reference: CollectionReference?
private let storage = Storage.storage().reference()
// private var messages = [Constants.MessageFields]()
//snapshot private var messages: [Constants.MessageFields] = []
private var messageListener: ListenerRegistration?
// var db:Firestore!
#IBOutlet weak var banner: GADBannerView!
#IBOutlet weak var clientTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.clientTable.register(UITableViewCell.self, forCellReuseIdentifier: "tableViewCell")
// clientTable.delegate = self
//clientTable.dataSource = self
//db = Firestore.firestore()
ref = db.collection("messages").document("hello").collection("newmessages").document("2").collection("hellos").document("K").collection("messages")
ref2 = db.collection("messages").document("hello").collection("newmessages").document("2").collection("hellos").document("K").collection("messages").document()
configureDatabase()
configureStorage()
configureRemoteConfig()
fetchConfig()
loadAd()
}
deinit {
if let refhandle = _refHandle {
let listener = ref.addSnapshotListener { querySnapshot, error in
}
listener.remove()
}
}
func configureDatabase() {
db.collection("messages").document("hello").collection("newmessages").document("2").collection("hellos").document("K").collection("messages").addSnapshotListener { querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
/* let name = documents.map { $0["name"]!}
let text = documents.map { $0["text"]!}
let photourl = documents.map { $0["photoUrl"]!}
print(name)
print(text)
print(photourl)*/
self.messages.append(contentsOf: documents)
// self.clientTable.insertRows(at: [IndexPath(row: self.messages.count-1, section: 0)], with: .automatic)
//self.clientTable.reloadData()
}
}
func configureStorage() {
storageRef = Storage.storage().reference()
}
func configureRemoteConfig() {
remoteConfig = RemoteConfig.remoteConfig()
let remoteConfigSettings = RemoteConfigSettings(developerModeEnabled: true)
remoteConfig.configSettings = remoteConfigSettings
}
func fetchConfig() {
var expirationDuration: Double = 3600
// If in developer mode cacheExpiration is set to 0 so each fetch will retrieve values from
// the server.
if self.remoteConfig.configSettings.isDeveloperModeEnabled {
expirationDuration = 0
}
remoteConfig.fetch(withExpirationDuration: expirationDuration) { [weak self] (status, error) in
if status == .success {
print("Config fetched!")
guard let strongSelf = self else { return }
strongSelf.remoteConfig.activateFetched()
let friendlyMsgLength = strongSelf.remoteConfig["friendly_msg_length"]
if friendlyMsgLength.source != .static {
strongSelf.msglength = friendlyMsgLength.numberValue!
print("Friendly msg length config: \(strongSelf.msglength)")
}
} else {
print("Config not fetched")
if let error = error {
print("Error \(error)")
}
}
}
}
#IBAction func didPressFreshConfig(_ sender: AnyObject) {
fetchConfig()
}
#IBAction func didSendMessage(_ sender: UIButton) {
_ = textFieldShouldReturn(textField)
}
#IBAction func didPressCrash(_ sender: AnyObject) {
print("Crash button pressed!")
Crashlytics.sharedInstance().crash()
}
func inviteFinished(withInvitations invitationIds: [String], error: Error?) {
if let error = error {
print("Failed: \(error.localizedDescription)")
} else {
print("Invitations sent")
}
}
func loadAd() {
self.banner.adUnitID = kBannerAdUnitID
self.banner.rootViewController = self
self.banner.load(GADRequest())
}
// UITableViewDataSource protocol methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Dequeue cell
let cell = self.clientTable .dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath)
// Unpack message from Firebase DataSnapshot
let messageSnapshot: DocumentSnapshot! = self.messages[indexPath.row]
guard let message = messageSnapshot as? [String:String] else { return cell }
let name = message[Constants.MessageFields.name] ?? ""
if let imageURL = message[Constants.MessageFields.imageURL] {
if imageURL.hasPrefix("gs://") {
Storage.storage().reference(forURL: imageURL).getData(maxSize: INT64_MAX) {(data, error) in
if let error = error {
print("Error downloading: \(error)")
return
}
DispatchQueue.main.async {
cell.imageView?.image = UIImage.init(data: data!)
cell.setNeedsLayout()
}
}
} else if let URL = URL(string: imageURL), let data = try? Data(contentsOf: URL) {
cell.imageView?.image = UIImage.init(data: data)
}
cell.textLabel?.text = "sent by: \(name)"
} else {
let text = message[Constants.MessageFields.text] ?? ""
cell.textLabel?.text = name + ": " + text
cell.imageView?.image = UIImage(named: "ic_account_circle")
if let photoURL = message[Constants.MessageFields.photoURL], let URL = URL(string: photoURL),
let data = try? Data(contentsOf: URL) {
cell.imageView?.image = UIImage(data: data)
}
}
return cell
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard let text = textField.text else { return true }
textField.text = ""
view.endEditing(true)
let data = [Constants.MessageFields.text: text]
sendMessage(withData: data)
return true
}
func sendMessage(withData data: [String: String]) {
var mdata = data
mdata[Constants.MessageFields.name] = Auth.auth().currentUser?.displayName
if let photoURL = Auth.auth().currentUser?.photoURL {
mdata[Constants.MessageFields.photoURL] = photoURL.absoluteString
}
// Push data to Firebase Database
self.ref.document().setData(mdata, merge: true) { (err) in
if let err = err {
print(err.localizedDescription)
}
print("Successfully set newest city data")
}
}
// MARK: - Image Picker
#IBAction func didTapAddPhoto(_ sender: AnyObject) {
let picker = UIImagePickerController()
picker.delegate = self
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
picker.sourceType = .camera
} else {
picker.sourceType = .photoLibrary
}
present(picker, animated: true, completion:nil)
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion:nil)
guard let uid = Auth.auth().currentUser?.uid else { return }
// if it's a photo from the library, not an image from the camera
if #available(iOS 8.0, *), let referenceURL = info[.originalImage] as? URL {
let assets = PHAsset.fetchAssets(withALAssetURLs: [referenceURL], options: nil)
let asset = assets.firstObject
asset?.requestContentEditingInput(with: nil, completionHandler: { [weak self] (contentEditingInput, info) in
let imageFile = contentEditingInput?.fullSizeImageURL
let filePath = "\(uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000))/\((referenceURL as AnyObject).lastPathComponent!)"
guard let strongSelf = self else { return }
strongSelf.storageRef.child(filePath)
.putFile(from: imageFile!, metadata: nil) { (metadata, error) in
if let error = error {
let nsError = error as NSError
print("Error uploading: \(nsError.localizedDescription)")
return
}
strongSelf.sendMessage(withData: [Constants.MessageFields.imageURL: strongSelf.storageRef.child((metadata?.path)!).description])
}
})
} else {
guard let image = info[.originalImage] as? UIImage else { return }
let imageData = image.jpegData(compressionQuality:0.8)
let imagePath = "\(uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000)).jpg"
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
self.storageRef.child(imagePath)
.putData(imageData!, metadata: metadata) { [weak self] (metadata, error) in
if let error = error {
print("Error uploading: \(error)")
return
}
guard let strongSelf = self else { return }
strongSelf.sendMessage(withData: [Constants.MessageFields.imageURL: strongSelf.storageRef.child((metadata?.path)!).description])
}
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion:nil)
}
#IBAction func signOut(_ sender: UIButton) {
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
dismiss(animated: true, completion: nil)
} catch let signOutError as NSError {
print ("Error signing out: \(signOutError.localizedDescription)")
}
}
func showAlert(withTitle title: String, message: String) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title,
message: message, preferredStyle: .alert)
let dismissAction = UIAlertAction(title: "Dismiss", style: .destructive, handler: nil)
alert.addAction(dismissAction)
self.present(alert, animated: true, completion: nil)
}
}
}
Edit
perform this block of code on main thread
for doc in documents {
self.messages.append(doc)
self.clientTable.insertRows(at: [IndexPath(row: self.messages.count-1, section: 0)], with: .automatic)
}
This should work..

Firebase ServerValue.timestamp() continuously changes in firebase database

I am Trying to add an instance of ServerValue.timestamp() into my firebase database, when i run the app , the time stamps continuously increase here is the code, im not sure how to stop the timestamp from increasing in firebase
here is my custom class and my tableview class
class Story
{
var text: String = ""
var timestamp: String = ""
let ref: DatabaseReference!
init(text: String) {
self.text = text
ref = Database.database().reference().child("People").child("HomeFeed").child("Posts").childByAutoId()
}
init(snapshot: DataSnapshot)
{
ref = snapshot.ref
if let value = snapshot.value as? [String : Any] {
text = value["Post"] as! String
ref.updateChildValues(["timestamp":ServerValue.timestamp()])
let id = ref.key
Database.database().reference().child("People").child("HomeFeed").child("Posts").child("\(id)").child("timestamp").observeSingleEvent(of: .value) { (snapshot) in
let dope = snapshot.value as! Double
let x = dope / 1000
let date = NSDate(timeIntervalSince1970: x)
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .medium
DispatchQueue.main.async {
self.timestamp = formatter.string(from: date as Date)
self.timestamp = "\(value["timestamp"])"
}
}
}
}
func save() {
ref.setValue(toDictionary())
}
func toDictionary() -> [String : Any]
{
return [
"Post" : text,
"timestamp" : timestamp
]
}
}
here is the tableview class
class TableViewController: UIViewController,UITableViewDataSource, UITableViewDelegate {
let databaseRef = Database.database().reference()
#IBOutlet weak var tableView: UITableView!
var rub: StorageReference!
#IBAction func createpost(_ sender: Any) {
self.databaseRef.child("ProfileInfo").child(Auth.auth().currentUser!.uid).child("ProfilePic").observe(DataEventType.value) { (snapshot) in
let profpic = snapshot.value as? String
self.databaseRef.child("ProfileInfo").child(Auth.auth().currentUser!.uid).child("Full Name").observe(DataEventType.value) { (snapshot) in }
let fullname = snapshot.value as? String
if profpic == nil && fullname == nil {
let alert = UIAlertController(title: "Need to create profile", message: nil, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "To create profile", style: UIAlertActionStyle.default, handler: { action in self.performSegue(withIdentifier: "ToCreateprof", sender: nil)}))
alert.addAction(UIAlertAction(title: "Dissmiss", style: UIAlertActionStyle.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}else {
self.performSegue(withIdentifier: "ToPost", sender: nil)
}
} //if no prof pic and name, no posting
}
#IBAction func toCreateorprofile(_ sender: Any) {
self.databaseRef.child("ProfileInfo").child(Auth.auth().currentUser!.uid).child("ProfilePic").observe(DataEventType.value) { (snapshot) in
let profpic = snapshot.value as? String
self.databaseRef.child("ProfileInfo").child(Auth.auth().currentUser!.uid).child("Full Name").observe(DataEventType.value) { (snapshot) in }
let fullname = snapshot.value as? String
if profpic != nil && fullname != nil {
self.performSegue(withIdentifier: "olduser", sender: nil)
}else {
self.performSegue(withIdentifier: "ToCreateprof", sender: nil)
}
}
}
let storiesRef = Database.database().reference().child("People").child("HomeFeed").child("Posts")
var stories = [Story]()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// download stories
storiesRef.observe(.value, with: { (snapshot) in
self.stories.removeAll()
for child in snapshot.children {
let childSnapshot = child as! DataSnapshot
let story = Story(snapshot: childSnapshot)
self.stories.insert(story, at: 0)
}
self.tableView.reloadData()
})
}
#objc func handleRefresh(_ refreshControl: UIRefreshControl) {
self.tableView.reloadData()
refreshControl.endRefreshing()
}
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action:
#selector(TableViewController.handleRefresh(_:)),
for: UIControlEvents.valueChanged)
refreshControl.tintColor = UIColor.purple
return refreshControl
}()
override func viewDidLoad()
{
super.viewDidLoad()
self.tableView.reloadData()
self.tableView.addSubview(self.refreshControl)
tableView.delegate = self
tableView.dataSource = self
self.tableView.estimatedRowHeight = 92.0
self.tableView.rowHeight = UITableViewAutomaticDimension
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return stories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Story Cell", for: indexPath) as! StoryTableviewcell
let story = stories[indexPath.row]
cell.story = story
self.databaseRef.child("ProfileInfo").child(Auth.auth().currentUser!.uid).child("Full Name").observe(.value) { (snapshot) in
let name = snapshot.value as? String
if name != nil {
cell.fullnamepost.text = name
}
}
rub = Storage.storage().reference().storage.reference(forURL:"gs://people-3b93c.appspot.com").child("ProfilePic").child(Auth.auth().currentUser!.uid)
if rub != nil {
// Create a UIImage, add it to the array
rub.downloadURL(completion: { (url, error) in
if error != nil {
print(error?.localizedDescription as Any)
return
}
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print(error as Any)
return
}
guard let imageData = UIImage(data: data!) else { return }
DispatchQueue.main.async {
cell.profimage.image = imageData
}
}).resume()
})
}
return cell
}
}

how do I add a comment to it like in Instagram and allow other users to comment on the pictures as well

Hi when posting a picture in my swift 3 and firebase app how do I add a comment to it like before the picture is actually posted? Like in Instagram and how do I allow other users to comment on the pictures that other people have posted as well? below is every code I have on posting
Post Cell
import UIKit
import Firebase
import FirebaseStorage
import FirebaseDatabase
import SwiftKeychainWrapper
class PostCell: UITableViewCell {
#IBOutlet weak var userImg: UIImageView!
#IBOutlet weak var username: UILabel!
#IBOutlet weak var postImg: UIImageView!
#IBOutlet weak var likesLbl: UILabel!
var post: Post!
var userPostKey: FIRDatabaseReference!
let currentUser = KeychainWrapper.standard.string(forKey: "uid")
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configCell(post: Post, img: UIImage? = nil, userImg: UIImage? = nil) {
self.post = post
self.likesLbl.text = "\(post.likes)"
self.username.text = post.username
if img != nil {
self.postImg.image = img
} else {
let ref = FIRStorage.storage().reference(forURL: post.postImg)
ref.data(withMaxSize: 10 * 10000, completion: { (data, error) in
if error != nil {
print(error)
} else {
if let imgData = data {
if let img = UIImage(data: imgData){
self.postImg.image = img
}
}
}
})
}
if userImg != nil {
self.postImg.image = userImg
} else {
let ref = FIRStorage.storage().reference(forURL: post.userImg)
ref.data(withMaxSize: 100000000, completion: { (data, error) in
if error != nil {
print("couldnt load img")
} else {
if let imgData = data {
if let img = UIImage(data: imgData){
self.userImg.image = img
}
}
}
})
}
_ = FIRDatabase.database().reference().child("users").child(currentUser!).child("likes").child(post.postKey)
}
#IBAction func liked(_ sender: Any) {
let likeRef = FIRDatabase.database().reference().child("users").child(currentUser!).child("likes").child(post.postKey)
likeRef.observeSingleEvent(of: .value, with: { (snapshot) in
if let _ = snapshot.value as? NSNull {
self.post.adjustLikes(addlike: true)
likeRef.setValue(true)
} else {
self.post.adjustLikes(addlike: false)
likeRef.removeValue()
}
})
}
}
FeedVC
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseStorage
import SwiftKeychainWrapper
import CoreImage
class FeedVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var postBtn: UIButton!
var posts = [Post]()
var post: Post!
var imagePicker: UIImagePickerController!
var imageSelected = false
var selectedImage: UIImage!
var userImage: String!
var userName: String!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.delegate = self
FIRDatabase.database().reference().child("posts").observe(.value, with: {(snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
self.posts.removeAll()
for data in snapshot {
print(data)
if let postDict = data.value as? Dictionary<String, AnyObject> {
let key = data.key
let post = Post(postKey: key, postData: postDict)
self.posts.append(post)
}
}
}
self.tableView.reloadData()
})
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = posts[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell {
cell.configCell(post: post)
return cell
} else {
return PostCell()
}
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
selectedImage = image
imageSelected = true
} else {
print("A valid image wasnt selected")
}
imagePicker.dismiss(animated: true, completion: nil)
guard imageSelected == true else {
print("An image must be selected")
return
}
if let imgData = UIImageJPEGRepresentation(selectedImage, 0.2) {
let imgUid = NSUUID().uuidString
let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpeg"
FIRStorage.storage().reference().child("post-pics").child(imgUid).put(imgData, metadata: metadata) { (metadata, error) in
if error != nil {
print("image did not save to firebase storage")
} else {
print("uploded to firebase storage")
let downloadURL = metadata?.downloadURL()?.absoluteString
if let url = downloadURL {
self.postToFirebase(imgUrl: url)
}
}
}
}
}
func postToFirebase(imgUrl: String) {
let userID = FIRAuth.auth()?.currentUser?.uid
FIRDatabase.database().reference().child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let data = snapshot.value as! Dictionary<String, AnyObject>
let username = data["username"]
let userImg = data["userImg"]
let post: Dictionary<String, AnyObject> = [
"username": username as AnyObject,
"userImg": userImg as AnyObject,
"imageUrl": imgUrl as AnyObject,
"likes": 0 as AnyObject
]
let firebasePost = FIRDatabase.database().reference().child("posts").childByAutoId()
firebasePost.setValue(post)
self.imageSelected = false
self.tableView.reloadData()
}) { (error) in
print(error.localizedDescription)
}
}
#IBAction func postImageTapped(_ sender: AnyObject)
{
let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
self.openCamera()
}))
alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
self.openGallary()
}))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func openCamera()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera))
{
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
else
{
let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func openGallary()
{
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
#IBAction func SignOutPressed(_ sender: AnyObject) {
try! FIRAuth.auth()?.signOut()
KeychainWrapper.standard.removeObject(forKey: "uid")
dismiss(animated: true, completion: nil)
}
}
Post
import Foundation
import Firebase
import FirebaseDatabase
class Post {
private var _username: String!
private var _userImg: String!
private var _postImg: String!
private var _likes: Int!
private var _postKey: String!
private var _postRef: FIRDatabaseReference!
var username: String {
return _username
}
var userImg: String {
return _userImg
}
var postImg: String {
get {
return _postImg
} set {
_postImg = newValue
}
}
var likes: Int {
return _likes
}
var postKey: String {
return _postKey
}
init(imgUrl: String, likes: Int, username: String, userImg: String) {
_likes = likes
_postImg = imgUrl
_username = username
_userImg = userImg
}
init(postKey: String, postData: Dictionary<String, AnyObject>) {
_postKey = postKey
if let username = postData["username"] as? String {
_username = username
}
if let userImg = postData["userImg"] as? String {
_userImg = userImg
}
if let postImage = postData["imageUrl"] as? String {
_postImg = postImage
}
if let likes = postData["likes"] as? Int {
_likes = likes
}
_postRef = FIRDatabase.database().reference().child("posts").child(_postKey)
}
func adjustLikes(addlike: Bool) {
if addlike {
_likes = likes + 1
} else {
_likes = likes - 1
}
_postRef.child("likes").setValue(_likes)
}
}
Hope this is enough information provided.
Still looking for answer? You could probably add some king of view to your post that would hold comments. Instagram only shows a few and then displays the comments in a separate viewController

Login & Signup iOS Swift - Core Data

I want to create login and signup functions within Swift using Core Data.
This is my code to store the data in the signupVC;
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext
let newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
newUser.setValue(txtUsername.text, forKey: "username")
newUser.setValue(txtPassword.text, forKey: "password")
newUser.setValue(txtEmailAdd.text, forKey: "email")
do {
try context.save()
} catch {}
print(newUser)
print("Object Saved.")
This is the code in the LoginVC;
#IBAction func signinTapp(sender: UIButton) {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false
request.predicate = NSPredicate(format: "username = %#", "" + txtUsername.text!)
let results:NSArray = try! context.executeFetchRequest(request)
if(results.count > 1){
let res = results[0] as! NSManagedObject
txtUsername.text = res.valueForKey("username") as! String
txtPassword.text = res.valueForKey("password") as! String
//for res in results {
// print(res)
}else{
print("Incorrect username and password")
}
}
Can anyone please advise my the best way forward? - I just need to retrieve the saved core data and check if it matches.
Here is my Core Data model:
look into below code
func CheckForUserNameAndPasswordMatch (userName : String, password : String) ->Bool
{
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var managedObjectContext = appDelegate.managedObjectContext
var predicate = NSPredicate (format:"userName = %#" ,userName)
var fetchRequest = NSFetchRequest ( entityName: "UserEntity")
fetchRequest.predicate = predicate
var error : NSError? = nil
var fetchRecult = managedObjectContext?.executeFetchRequest(fetchRequest, error: &error)
if fetchRecult?.count>0
{
var objectEntity : UserEntity = fetchRecult?.first as! UserEntity
if objectEntity.userName == userName && objectEntity.password == password
{
return true // Entered Username & password matched
}
else
{
return false //Wrong password/username
}
}
else
{
return false
}
}
Moreover it would not be good to save password in device if you are working on any enterprise product.
import UIKit
import CoreData
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var txt_username: UITextField!
#IBOutlet var txt_password: UITextField!
var result = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func Log_in(_ sender: Any)
{
if txt_username.text == "" && txt_password.text == ""
{
let alert = UIAlertController(title: "Information", message: "Please enter all the fields", preferredStyle: .alert)
let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(ok)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
else
{
self.CheckForUserNameAndPasswordMatch(username : txt_username.text! as String, password : txt_password.text! as String)
}
}
func CheckForUserNameAndPasswordMatch( username: String, password : String)
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let fetchrequest = NSFetchRequest<NSFetchRequestResult>(entityName: "LoginDetails")
let predicate = NSPredicate(format: "username = %#", username)
fetchrequest.predicate = predicate
do
{
result = try context.fetch(fetchrequest) as NSArray
if result.count>0
{
let objectentity = result.firstObject as! LoginDetails
if objectentity.username == username && objectentity.password == password
{
print("Login Succesfully")
}
else
{
print("Wrong username or password !!!")
}
}
}
catch
{
let fetch_error = error as NSError
print("error", fetch_error.localizedDescription)
}
}
}
Registration page
==================>
import UIKit
import CoreData
class RegistrationPage: UIViewController, UITextFieldDelegate {
#IBOutlet var txt_user: UITextField!
#IBOutlet var txt_mailid: UITextField!
#IBOutlet var txt_pwd: UITextField!
#IBOutlet var txt_cpwd: UITextField!
#IBOutlet var txt_phone: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func register(_ sender: Any)
{
if txt_user.text == "" || txt_mailid.text == "" || txt_pwd.text == "" || txt_cpwd.text == "" || txt_phone.text == ""
{
let alert = UIAlertController(title: "Information", message: "Its Mandatort to enter all the fields", preferredStyle: .alert)
let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(ok)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
else if (txt_pwd.text != txt_cpwd.text)
{
let alert = UIAlertController(title: "Information", message: "Password does not match", preferredStyle: .alert
)
let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(ok)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
else
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let new_user = NSEntityDescription.insertNewObject(forEntityName: "LoginDetails", into: context)
new_user.setValue(txt_user.text, forKey: "username")
new_user.setValue(txt_mailid.text, forKey: "mailid")
new_user.setValue(txt_pwd.text, forKey: "password")
new_user.setValue(txt_phone.text, forKey: "phone")
do
{
try context.save()
print("Registered Sucessfully")
}
catch
{
let Fetcherror = error as NSError
print("error", Fetcherror.localizedDescription)
}
}
self.navigationController?.popViewController(animated: true)
}
}
Is username unique as per database constraint? Then, you will never get more than one result from the fetch.
If you use
if let user = results.first where
user.pass == (passField.text ?? "") {
// login
}
else {
// no login
}
you'd be better of.
Also, do not set the field's from the db; check if they are equal.
Also, please realize that such a sign-up will be valid only on a per-app-installation basis.
For production security, store only hashes of passwords.
It is very simple to make a user login system using core data
First you have to create a project and include core data in it. Then you have to add to the .xcdatamodeld file an entity with some attributes.
Here is a picture of how does the file looks like:
CoreData.xcdatamodeld File
Here is the example code:
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newUser = NSEntityDescription.insertNewObject(forEntityName: "Users", into: context)
newUser.setValue("Joe", forKey: "username")
newUser.setValue("JoeTheLazy", forKey: "password")
newUser.setValue(48, forKey: "age")
do {
try context.save()
print("saved")
} catch {
print ( "Some Error has been Detected")
}
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.returnsObjectsAsFaults = false
do {
let reusutls = try context.fetch(request)
if reusutls.count > 0 {
for r in reusutls as! [NSManagedObject]
{
if let username = r.value(forKey: "username") as? String
{print(username)}
}
}
else {print("Cannot fetch results")
}
}
catch {
print("error")
}
}
#IBOutlet weak var usrName: UITextField!
#IBOutlet weak var passWord: UITextField!
#IBOutlet weak var showList: UILabel!
#IBOutlet weak var errorText: UILabel!
#IBAction func tryLogin(_ sender: UIButton) {
let x = usrName.text
let y = passWord.text
if (x! == "" || y! == "")
{
print ("I am here")
errorText.text = "user name or password empty "
}
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.predicate = NSPredicate(format: "username = %#", usrName.text!)
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
let passwordFromData = data.value(forKey: "password") as! String
if y! == passwordFromData
{
errorText.text = " You have been Granted Access!"
}
}
}catch {
print("Failed")
}
}
#IBAction func ShowData(_ sender: UIButton) {
var listTprint = ""
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.returnsObjectsAsFaults = false
do {
let reusutls = try context.fetch(request)
if reusutls.count > 0 {
for r in reusutls as! [NSManagedObject]
{
if let username = r.value(forKey: "username") as? String
{listTprint.append(username)
listTprint.append(" ")
let password = r.value(forKey: "password") as? String
listTprint.append(password!)
listTprint.append(" ")
}
}
}
else
{print("Cannot fetch results")}
}
catch {
print("Error")
}
showList.text! = listTprint
}
Coredata save fetch update delete
==================================>
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var my_table: UITableView!
var playerdata = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool)
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let fetch_data = NSFetchRequest<NSManagedObject>(entityName: "PlayerDetails")
do
{
self.playerdata = try context.fetch(fetch_data as! NSFetchRequest<NSFetchRequestResult>) as! NSMutableArray
}
catch let error as NSError
{
print(error.localizedDescription)
}
self.my_table.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return playerdata.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = my_table.dequeueReusableCell(withIdentifier: "hari") as! TableViewCell123
let playerdetails = self.playerdata[indexPath.row]
cell.playername.text = (playerdetails as AnyObject) .value(forKey: "player_name")as? String
cell.playerid.text = (playerdetails as AnyObject) .value(forKey: "player_id")as? String
cell.playerteam.text = (playerdetails as AnyObject) .value(forKey: "player_team")as? String
cell.playerimage.image = UIImage(data: ((playerdetails as AnyObject) .value(forKey: "player_img")as? Data)!)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
self.performSegue(withIdentifier: "datapass", sender: self)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
if(editingStyle == .delete)
{
let user = self.playerdata[indexPath.row] as! NSManagedObject
context.delete(user)
do
{
try context.save()
self.playerdata.removeObject(at: indexPath.row)
my_table.deleteRows(at: [indexPath], with: .fade)
}
catch let error as NSError
{
print("error",error.localizedDescription)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "datapass"
{
let vc2 = segue.destination as! ViewController2
let index = my_table.indexPathForSelectedRow
let data = self.playerdata[(index?.row)!]
vc2.dataupdate = data as! NSManagedObject
}
}
}
VIEWCONTROLLER - 2
===================>
import UIKit
import CoreData
class ViewController2: UIViewController
{
#IBOutlet var txt_playername: UITextField!
#IBOutlet var txt_playerid: UITextField!
#IBOutlet var txt_playerteam: UITextField!
#IBOutlet var img_playerimage: UIImageView!
var dataupdate = NSManagedObject()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if (dataupdate != nil)
{
txt_playername.text = dataupdate.value(forKey: "player_name")as? String
txt_playerid.text = dataupdate.value(forKey: "player_id")as? String
txt_playerteam.text = dataupdate.value(forKey: "player_team")as? String
img_playerimage.image = UIImage(data: dataupdate.value(forKey: "player_img") as! Data)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func save_update(_ sender: Any)
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
if (dataupdate != nil)
{
dataupdate.setValue(self.txt_playername.text, forKey: "player_name")
dataupdate.setValue(self.txt_playerid.text, forKey: "player_id")
dataupdate.setValue(self.txt_playerteam.text, forKey: "player_team")
let img_data = UIImageJPEGRepresentation(self.img_playerimage.image!, 1.0)
dataupdate.setValue(img_data, forKey: "player_img")
}
else
{
let newplayer = NSEntityDescription.insertNewObject(forEntityName: "PlayerDetails", into: context)
newplayer.setValue(self.txt_playername.text, forKey: "player_name")
newplayer.setValue(self.txt_playerid.text, forKey: "player_id")
newplayer.setValue(self.txt_playerteam.text, forKey: "player_team")
let img_data = UIImageJPEGRepresentation(self.img_playerimage.image!, 1.0)
newplayer.setValue(img_data, forKey: "player_img")
}
do
{
try context.save()
}
catch let error as NSError
{
print(error.localizedDescription)
}
self.dismiss(animated: true, completion: nil)
}
}

Resources