How to Clear Shared Dictionary which is causing saved values not to clear even when I login with other user - swift

How can I clear the shared dictionary on logout in which I am saving login response?
Here is the code I am doing on getting status 1.
if(status == 1)
{
DispatchQueue.main.async {
GAReusableClass.sharedInstance.hideActivityIndicator()
UserDefaults.standard.set(self.DataDict, forKey:MaindataKey)
let Dict = self.mainDict[KData] as! [String: AnyObject]
print("self.DataDict", self.DataDict)
let User_ID = Dict[KUuid]as! String
print(User_ID)
let HMACSECRETKEY = self.deviceToken + "+" + User_ID
kHMACKey = HMACSECRETKEY
let cipher:String = CryptoHelper.encrypt(input:HMACSECRETKEY)!;
print(HMACSECRETKEY)
UserDefaults.standard.setValue(cipher, forKey:HmacKey)
UserDefaults.standard.set(true, forKey: "isLogin")
GAloginUserInfo.shared.saveUserInfo(dict: Dict )
let tabar = self.storyboard?.instantiateViewController(withIdentifier: "GAtHomeTabbarViewController") as! GAtHomeTabbarViewController
self.navigationController?.pushViewController(tabar, animated: true)
}
Here is the shared dictionary which I am using to save the values of login response.
import UIKit
import Firebase
class GAloginUserInfo: NSObject {
var loginUserMobileNo : String?
var loginUserId : String?
var loginUserUuid : String?
var loginUserCountry : String?
var loginUserCountryCode : String?
var loginUserEmail : String?
var loginUserlatitude : String?
var loginUserLongitude : String?
var loginUserName : String?
var loginUserQrcode : String?
var loginUserProfilePic : String?
var isverify : String?
var loginPassword : String?
var dateOfBirth: String?
var earnedPoints:String?
var loginUserGender:String?
var loginUserFollowers:Int = 0
static let shared = GAloginUserInfo()
func saveUserInfo (dict : [String : AnyObject?] ) {
if let loginUserMobileNo = dict["mobile"] as? String {
self.loginUserMobileNo = loginUserMobileNo
}
if let loginUserId = dict["id"] as? String {
self.loginUserId = loginUserId
}
if let loginUserUuid = dict["uuid"] as? String {
self.loginUserUuid = loginUserUuid
print(loginUserUuid)
}
if let loginUserCountry = dict["country"] as? String {
self.loginUserCountry = loginUserCountry
}
if let loginUserCountryCode = dict["country_code"] as? String {
self.loginUserCountryCode = loginUserCountryCode
}
if let loginUserEmail = dict["email"] as? String {
self.loginUserEmail = loginUserEmail
}
if let loginUserProfilePic = dict["profile_pic"] as? String {
self.loginUserProfilePic = loginUserProfilePic
}
if let loginUserLongitude = dict["logitude"] as? String {
self.loginUserLongitude = loginUserLongitude
}
if let loginUserName = dict["name"] as? String {
self.loginUserName = loginUserName
}
if let loginUserQrcode = dict["qr_code"] as? String {
self.loginUserQrcode = loginUserQrcode
}
if let Password = dict["password"] as? String{
self.loginPassword = Password
}
if let dateOfBirth = dict["dob"] as? String{
self.dateOfBirth = dateOfBirth
}
if let earnedPoints = dict["points"] as? String{
let myDouble = Double(earnedPoints)
let doubleStr = String(format: "%.2f", myDouble!)
self.earnedPoints = doubleStr
}
if let loginUserGender = dict["gender"] as? String{
self.loginUserGender = loginUserGender
}
if let loginUserFollowers = dict["followersCount"] as? Int{
self.loginUserFollowers = loginUserFollowers
}
}
}
Actually, the problem is when I log out and log in again with some other user it still shows some values of the previous user. I am clearing the userdefaults on the logout function. but I don't know how to clear this type of shared dictionary.

Use removeObject(forKey:)
to remove the values stored from user defaults in Logout method
UserDefaults.standard.removeObject(forKey: MaindataKey)
UserDefaults.standard.removeObject(forKey: HmacKey)
UserDefaults.standard.set(false, forKey: "isLogin")
Create a method to remove the values from the singleton class like this
extension GAloginUserInfo {
func removeUserInfo() {
self.loginUserMobileNo = nil
self.loginUserId = nil
self.loginUserUuid = nil
self.loginUserCountry = nil
self.loginUserCountryCode = nil
self.loginUserEmail = nil
self.loginUserlatitude = nil
self.loginUserLongitude = nil
self.loginUserName = nil
self.loginUserQrcode = nil
self.loginUserProfilePic = nil
self.isverify = nil
self.loginPassword = nil
self.dateOfBirth = nil
self.earnedPoints = nil
self.loginUserGender = nil
self.loginUserFollowers = 0
}
}
and call this method in logout
GAloginUserInfo.shared.removeUserInfo()

Related

How to get Firebase data as a model in swift?

I am trying to get data from firebase and use it as a model that I created.
Here is my model;
class UserData{
var nickname : String = ""
var onesignal_player_id : String = ""
var step_count : Int = 0
var total_point : Int = 0
var competitions : [String:Competition] = [String:Competition]()
}
class Competition{
var end_date : String = ""
var gift : String = ""
var id: String = ""
var name: String = ""
var users : [String:Int] = [:]
}
and this is my function;
func getFirebaseData() {
ref = Database.database().reference()
ref.child("users").child("HXXNCXf6RRS4WVO12shZ3j15BnG3").observe(.value) { (snapshot) in
if let snapshotValue = snapshot.value as? Dictionary<String,Any> {
//change userData with the snapshotValue
self.userData.nickname = snapshotValue["nickname"] as! String
self.userData.step_count = snapshotValue["step_count"] as! Int
self.userData.total_point = snapshotValue["total_point"] as! Int
self.userData.onesignal_player_id = snapshotValue["onesignal_player_id"] as! String
self.userData.competitions = snapshotValue["competitions"] as! [String:Competition]
//reload UI with userData
print(self.userData.competitions)
} else {
print("An error occured while assigning snapshotValue to userData")
}
}
}
This code gave me error like this;
Could not cast value of type '__NSDictionaryM' (0x1f47ada20) to 'StepCounterApp.Competition' (0x1004c06f0).
2021-01-02 23:05:49.985711+0300 StepCounterApp[32511:3685645] Could not cast value of type '__NSDictionaryM' (0x1f47ada20) to 'StepCounterApp.Competition' (0x1004c06f0).
but when i comment out the line included self.userData.competitions from getFirebaseData function, everything works fine.
What should I do? How can I use firebase data as a model?
Finally here is my firebase data;
The problem is in your data model. Declare your model data like this
class UserData {
var nickname : String = ""
var onesignal_player_id : String = ""
var step_count : Int = 0
var total_point : Int = 0
var competitions : Competition = Competition()
}
class Competition{
var end_date : String = ""
var gift : String = ""
var id: String = ""
var name: String = ""
var users : [String:Int] = [:]
init() {
}
init(with dictionary: [String: Any]) {
self.end_date = dictionary["end_date"] as! String
self.gift = dictionary["gift"] as! String
self.id = dictionary["id"] as! String
self.name = dictionary["name"] as! String
self.users = dictionary["users"] as! [String:Int]
}
}
And inside the getFirebaseData funcation
self.userData.competitions = Competition(with: snapshotValue["competitions"] as! [String: Any])
The problem was in my data model and with the help of Raja Kishan's data model sugestion I fixed the problem.
First I changed the model little bit;
class UserData{
var nickname : String = ""
var onesignal_player_id : String = ""
var step_count : Int = 0
var total_point : Int = 0
var competitions : [String:Competition] = [String:Competition]()
}
class Competition{
var end_date : String = ""
var gift : String = ""
var id: Int = 0
var name: String = ""
var users : [String:Int] = [:]
init() {
}
init(with dictionary: [String: Any]) {
self.end_date = dictionary["end_date"] as! String
self.gift = dictionary["gift"] as! String
self.id = dictionary["id"] as! Int
self.name = dictionary["name"] as! String
self.users = dictionary["users"] as! [String:Int]
}
}
Than I add a childSnapshot to my method so I can work directly the "competitions";
func getFirebaseData() {
ref = Database.database().reference()
ref.child("users").child("HXXNCXf6RRS4WVO12shZ3j15BnG3").observe(.value) { [self] (snapshot) in
if let snapshotValue = snapshot.value as? [String:Any] {
//change userData with the snapshotValue
self.userData.nickname = snapshotValue["nickname"] as! String
self.userData.step_count = snapshotValue["step_count"] as! Int
self.userData.total_point = snapshotValue["total_point"] as! Int
self.userData.onesignal_player_id = snapshotValue["onesignal_player_id"] as! String
//******
//This part of the coded added for to solve the problem starting from here
let childSnap = snapshot.childSnapshot(forPath: "competitions")
if let childSnapValue = childSnap.value as? [String:Any] {
childSnapValue.forEach { (element) in
self.userData.competitions.updateValue(Competition(with: element.value as! [String:Any]), forKey: element.key)
}
} else {
print("something wrong with the childSnap")
}
//to here
//******
} else {
print("An error occured while assigning snapshotValue to userData")
}
}
}

Table view stucking a lot

I am using a tableView to show text only. Inside cell, I am using a UITextView with dynamic height and linkDetection with html text converted to attributedString.
I am parsing the html text to attributed text inside my model class below way:
if let nodeValue = dict["blurb_link"]{
blurb_link = nodeValue as? String
let attrString = NSMutableAttributedString(attributedString: (blurb_link?.html2AttributedString)!)
atr_blurb_link = attrString
}
html2AttributedString in an extension of String which returns an attributedString from html text.
I am populating my cell inside cell subclass via below way,
textViewBlurbLink.attributedText = model.atr_blurb_link
But the problem that is happening is, whenever a new cell is loaded, the tableview stucks for a fraction of second which make the tableView scrolling a bit jerky and disturbing to user.
There are no images, no videos no heavy task inside cell which can cause a jerky scroll. Please tell me what could be possible reason of this jerky and hiccup scrolling?
EDIT:
The layout of my cell is:
After getting response I have populated tableView below way:
TSNetworkManager.getDataFor(Request: dataRequest, success: {response in
//print(response.responseObject!)
let model = TSLatestModel.init(WithDictionary: response.responseObject as? [String : Any])
completion(model)
tblLatest.reloadData()
}, failure: {error in
onError(error)
})
and inside cellForRowAtIndexPath
let modelLatestDetails = model?.data![indexPath.section].items![indexPath.row]
cell.setupCellData(model: modelLatestDetails!)
Inside the setupCellData in tableViewCell subclass I am setting the text into textView.
EDIT2:
This the total codebase of my model class
class TSLatestModel: TSModelBase {
var data : [LatestListModel]?
override init(WithDictionary dictionary: [String : Any]?) {
super.init(WithDictionary: dictionary)
if let dict = dictionary{
if let nodeValue = dict["data"] {
data = [LatestListModel]()
for latest in nodeValue as! [Any]{
let model = LatestListModel.init(WithDictionary: latest as? [String:Any])
data?.append(model)
}
}
}
}
}
class LatestListModel: NSObject {
var storyname : String?
var main_title : String?
var color : String?
var issuedate : String?
var formatted_issue_date : String?
var id : String?
var cat_name : String?
var cat_id : String?
var order : Int?
var items : [TSLatestDetailsModel]?
var itemsModified : [TSLatestDetailsModel]?
init(WithDictionary dictionary: [String : Any]?) {
super.init()
if let dict = dictionary {
if let nodeValue = dict["items"] {
items = [TSLatestDetailsModel]()
itemsModified = [TSLatestDetailsModel]()
for item in nodeValue as! [Any] {
let model = TSLatestDetailsModel.init(WithDictionary: item as? [String : Any])
items?.append(model)
if !((item as! [String : Any])["one_liner"] as! String).isEmpty {
let filteredArray = itemsModified?.filter({$0.one_liner == ((item as! [String : Any])["one_liner"] as! String)})
if filteredArray?.count == 0 {
let model = TSLatestDetailsModel.init(WithDictionary: item as? [String : Any])
itemsModified?.append(model)
}
}
}
}
if let nodeValue = dict["item_list"] {
items = [TSLatestDetailsModel]()
itemsModified = [TSLatestDetailsModel]()
for item in nodeValue as! [Any] {
let model = TSLatestDetailsModel.init(WithDictionary: item as? [String : Any])
items?.append(model)
if !((item as! [String : Any])["one_liner"] as! String).isEmpty {
let filteredArray = itemsModified?.filter({$0.one_liner == ((item as! [String : Any])["one_liner"] as! String)})
if filteredArray?.count == 0 {
let model = TSLatestDetailsModel.init(WithDictionary: item as? [String : Any])
itemsModified?.append(model)
}
}
}
}
if let nodeValue = dict["_id"] {
storyname = nodeValue as? String
}
if let nodeValue = dict["order"] {
order = nodeValue as? Int
}
if let nodeValue = dict["category"] {
cat_id = (nodeValue as! [Any])[0] as? String
}
if let dictStoryType = dict["_id"] as? [String : Any] {
if let nodeValue = dictStoryType["issuedate"] {
issuedate = nodeValue as? String
}
if let nodeValue = dictStoryType["formated_issue_date_title"] {
formatted_issue_date = nodeValue as? String
}
if let nodeValue = dictStoryType["id"] {
id = nodeValue as? String
}
if let nodeValue = dictStoryType["category_name"] {
cat_name = nodeValue as? String
}
}
if let nodeValue = dict["name"] {
storyname = nodeValue as? String
}
if let nodeValue = dict["story"] {
storyname = nodeValue as? String
}
if let nodeValue = dict["main_title"] {
main_title = nodeValue as? String
}
if let nodeValue = dict["color"] {
color = nodeValue as? String
}
}
}
}
class TSLatestDetailsModel: NSObject {
var __v : Int?
var _id : String?
var title : String?
var topic_key : String?
var blurb : String?
var blurb_link : String?
var atr_blurb_link : NSMutableAttributedString?
var formated_issue_date : String?
var formated_issue_date_item : String?
var formated_issue_date_title : String?
var issue_link : String?
var issue_title : String?
var issue_date : String?
var one_liner : String?
var main_title : String?
var source : String?
var source_link : String?
var isActive : Bool?
var isDeleted : Bool?
var isfavourite : Bool?
var story_order_number : Int?
var story_type : String?
var categories : [String]?
var story_type_model : TSStoryTypeDetailsModel?
var favourite_category_id : String?
init(WithDictionary dictionary: [String : Any]?) {
super.init()
if let dict = dictionary{
if let nodeValue = dict["__v"]{
__v = nodeValue as? Int
}
if let nodeValue = dict["_id"]{
_id = nodeValue as? String
}
if let nodeValue = dict["title"]{
title = nodeValue as? String
}
if let nodeValue = dict["topic_key"]{
topic_key = nodeValue as? String
}
if let nodeValue = dict["blurb"]{
blurb = nodeValue as? String
}
if let nodeValue = dict["blurb_link"]{
blurb_link = nodeValue as? String
let attrString = NSMutableAttributedString(attributedString: (blurb_link?.html2AttributedString)!)
atr_blurb_link = attrString
}
if let nodeValue = dict["formated_issue_date"]{
formated_issue_date = nodeValue as? String
}
if let nodeValue = dict["issue_date"]{
issue_date = nodeValue as? String
}
if let nodeValue = dict["issue_link"]{
issue_link = nodeValue as? String
}
if let nodeValue = dict["issue_title"]{
issue_title = nodeValue as? String
}
if let nodeValue = dict["one_liner"]{
one_liner = nodeValue as? String
}
if let nodeValue = dict["main_title"]{
main_title = nodeValue as? String
}
if let nodeValue = dict["source"]{
source = nodeValue as? String
}
if let nodeValue = dict["source_link"]{
source_link = nodeValue as? String
}
if let nodeValue = dict["isActive"]{
isActive = nodeValue as? Bool
}
if let nodeValue = dict["isfavourite"]{
isfavourite = nodeValue as? Bool
}
if let nodeValue = dict["story_order_number"]{
story_order_number = nodeValue as? Int
}
if let nodeValue = dict["story_type"]{
story_type = nodeValue as? String
}
if let nodeValue = dict["formated_issue_date_title"]{
formated_issue_date_title = nodeValue as? String
}
if let nodeValue = dict["formated_issue_date_item"]{
formated_issue_date_item = nodeValue as? String
}
if let nodeValue = dict["favourite_category_ids"] {
if (nodeValue as! [String]).count > 0 {
favourite_category_id = (nodeValue as! [String])[0]
}
}
if let nodeValue = dict["story_type"] {
let model = TSStoryTypeDetailsModel.init(WithDictionary: nodeValue as? [String : Any])
story_type_model = model
}
if let nodeValue = dict["category"] {
categories = [String]()
for category in nodeValue as! [String] {
categories?.append(category)
}
}
}
}
}
The cellForRowAtIndexPath:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TSArchiveDetailsCell") as! TSArchiveDetailsCell
cell.delegate = self
if !((favoriteDetilsModel?.data![indexPath.section].items![indexPath.row].source!.isEmpty)!) {
cell.viewFav.isHidden = false
} else {
if favoriteDetilsModel?.data![indexPath.section].storyname?.lowercased() == "brush up" {
cell.viewFav.isHidden = false
} else {
cell.viewFav.isHidden = true
}
}
if isSayItOnRounds {
let modelLatestDetails = favoriteDetilsModel?.data![indexPath.section].items?.filter({$0._id! == selectedItemId})[0]
cell.setupCellData(model: modelLatestDetails!)
} else if isBrushUp {
let thirdBrushUpItemModel = favoriteDetilsModel?.data![indexPath.section].items![2]
if thirdBrushUpItemModel?._id == selectedItemId {
let modelLatestDetails = favoriteDetilsModel?.data![indexPath.section].items?.filter({$0._id == selectedItemId})
cell.setupCellData(model: modelLatestDetails![0])
} else {
let modelLatestDetails = favoriteDetilsModel?.data![indexPath.section].items![indexPath.row]
cell.setupCellData(model: modelLatestDetails!)
}
} else {
let modelLatestDetails = favoriteDetilsModel?.data![indexPath.section].items![indexPath.row]
cell.setupCellData(model: modelLatestDetails!)
}
return cell
}
Possible problems:
Cell layout. I need to see, how do you make layout and reuse cell.
Parsing data and drawing cells at the same time.
You need to create all data before (tableView.datasource = self or tableView.reloadData()). So, your [AttributedString] must be ready before reloading tableView. Do not parse data in cellfoRowAtIndexPath.
Also, check that tableView call cellfoRowAtIndexPath only one time for each cell during cell lifetime.

SWIFT4 Contextual type 'FPChat!.Type' cannot be used with dictionary literal

I need to initialize an object, and pass it through a prepareforsegue to another class.
Last line of the code below throws "Contextual type 'FPChat!.Type' cannot be used with dictionary literal"
if (segue.identifier == "chatmessages") {
let vc = segue.destination as! FPChatMessageViewController
//vc.currentChat = fPChat
}
}
fPchat = FPChat?
// Start the Chat
#IBAction func Chat(_ sender: UIButton) {
// Create a new entry in chats. This variable is passed with prepareforsegue
let chatRef = ref.child("chats").childByAutoId()
let chatId = chatRef.key
//fPchat = FPChat?
let fPchat = FPChat.currentChat(currentChatID: chatId)
Below chat class:
import Firebase
class FPChat {
var chatID = ""
var chatDate: Date!
var text = ""
var messages: [FPChatMessage]!
var author: FPUser!
var mine = true
// Calling FPChat.currentChat(id) I have back the FPChat object
static func currentChat(currentChatID: String) -> FPChat {
return FPChat(chatID: currentChatID)
}
private init(chatID: String) {
self.chatID = chatID
}
init(snapshot: DataSnapshot, andMessages messages: [FPChatMessage]) {
guard let value = snapshot.value as? [String: Any] else { return }
self.chatID = snapshot.key
if let text = value["text"] as? String {
self.text = text
}
guard let timestamp = value["timestamp"] as? Double else { return }
self.chatDate = Date(timeIntervalSince1970: (timestamp / 1_000.0))
guard let author = value["author"] as? [String: String] else { return }
self.author = FPUser(dictionary: author)
self.messages = messages
self.mine = self.author.userID == Auth.auth().currentUser?.uid
}
}
What I am doing wrong?

Firebase: How to put data in a child that's already created with childbyAutoID

people in my app sometimes needs to update the status of something. Now can you choose of 2 things: The so called "Rollerbank" is still there or the "Rollerbank" is removed. The users can create a data ref. The id that will be created by childbyAutoID. Now is my question how to get the right child and update some childs with a value. My post:
class Post {
let ref: DatabaseReference!
var TypeControle: String = ""
var Stad: String = ""
var Tijd: String = ""
var TijdControle: String = ""
var TijdControleniet: String = ""
var Latitude: String = ""
var Longitude: String = ""
var Extrainformatie: String = ""
var Staater: String = ""
var Staaternietmeer: String = ""
init(TypeControle: String) {
self.TypeControle = TypeControle
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Stad: String){
self.Stad = Stad
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Tijd: String) {
self.Tijd = Tijd
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Latitude: String) {
self.Latitude = Latitude
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Longitude: String) {
self.Longitude = Longitude
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Extrainformatie: String) {
self.Extrainformatie = Extrainformatie
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Staater: String) {
self.Staater = Staater
ref = Database.database().reference().child("Rollerbanken").child("Controletest").childByAutoId()
}
init(Staaternietmeer: String) {
self.Staaternietmeer = Staaternietmeer
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(TijdControle: String) {
self.TijdControle = TijdControle
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(TijdControleniet: String) {
self.TijdControleniet = TijdControleniet
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init() {
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(snapshot: DataSnapshot)
{
ref = snapshot.ref
if let value = snapshot.value as? [String : Any] {
TypeControle = value["TypeControle"] as! String
Stad = value["Stad"] as! String
Tijd = value["Tijd"] as! String
Latitude = value["Latitude"] as! String
Longitude = value["Longitude"] as! String
Extrainformatie = value["Extrainformatie"] as! String
Staater = value["Staater"] as! String
Staaternietmeer = value["Staaternietmeer"] as! String
TijdControle = value["TijdControle"] as! String
TijdControleniet = value["TijdControleniet"] as! String
}
}
func save() {
ref.setValue(toDictionary())
}
func toDictionary() -> [String : Any]
{
return [
"TypeControle" : TypeControle,
"Stad" : Stad,
"Tijd" : Tijd,
"Latitude" : Latitude,
"Longitude" : Longitude,
"Extrainformatie" : Extrainformatie,
"Staater" : Staater,
"Staaternietmeer" : Staaternietmeer,
"TijdControle" : TijdControle,
"TijdControleniet" : TijdControleniet
]
}
}
Data for the TableViewCell:
class ControleTableViewCell: UITableViewCell {
#IBOutlet weak var storyControle: UILabel!
#IBOutlet weak var storyTijd: UILabel!
var post: Post! {
didSet {
storyControle.text = "\(post.Staaternietmeer)"
storyTijd.text = "\(post.TijdControleniet)"
storyControle.text = "\(post.Staater)"
storyTijd.text = "\(post.TijdControle)"
}
}
How my update button looks like:
#IBAction func Update(_ sender: Any) {
let alertController1 = UIAlertController(title: "Update melden" , message: "De rollerbank", preferredStyle: .alert)
// Create the actions
let RollerbankAction1 = UIAlertAction(title: "Staat er nog steeds", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("Ja Pressed")
self.newStory.Staater = self.Staater
self.newStory.TijdControle = self.TijdControle
self.newStory.save()
}
let cancelAction1 = UIAlertAction(title: "Staat er niet meer", style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let Tijd = "\(hour) : \(minutes)"
self.newStory.Staaternietmeer = self.Staaternietmeer
self.newStory.TijdControleniet = Tijd
self.newStory.save()
}
alertController1.addAction(RollerbankAction1)
alertController1.addAction(cancelAction1)
self.present(alertController1, animated: true, completion: nil)
}
This is the Structure that i use. If i run all this code, the new data will go in a other childbyAutoID and thats not what i want. It just needs to update/setvalue in the cleare space named "Staaternietmeer" and "TijdControleniet". Can anybody help me with that?
You would then need to store the Push ID somewhere so that you can reuse it later.
To generate a unique Push ID you would use :
Database.database().reference().childByAutoId()
And to store it somewhere :
let postKey = Database.database().reference().childByAutoId().key
And then, say you need a method to share a post for example, and want to add this post to multiple nodes, that's how it may look like :
func sharePost(_ postContent: String, completion: #escaping (Bool) -> ()) {
guard let currentUserId = Auth.auth().currentUser?.uid else {
completion(false)
return
}
let postKey = Database.database().reference().childByAutoId().key
let postData: [String: Any] = [ "content": "blabla",
"author": currentUserId ]
let childUpdates: [String: Any] = ["users/\(currentUserId)/posts/\(postKey)": true,
"posts/\(postKey)": postData ]
Database.database().reference().updateChildValues(childUpdates, withCompletionBlock: { (error, ref) in
guard error == nil else {
completion(false)
return
}
completion(true)
})
}
Now to access the unique Push ID later on, you would use :
Database.database().reference().observe(.childAdded, with: { (snapshot) in
// Here you get the Push ID back :
let postKey = snapshot.key
// And others things that you need :
guard let author = snapshot.childSnapshot(forPath: "author").value as? String else { return }
guard let content = snapshot.childSnapshot(forPath: "content").value as? String else { return }
// Here you store your object (Post for example) in an array, and as you can see you initialize your object using the data you got from the snapshot, including the Push ID (`postKey`) :
posts.append(Post(id: postKey, content: content, author: author))
})

How to get and add to Syncano reference to user_profile

as in the title I have problem how adds to syncano reference to user_profile,
If someone could tell me a hint?
So this is my code:
func saveName() {
let Uerextra = userextra()
Uerextra.name = (self.dict.objectForKey("first_name") as? String)!
Uerextra.lastName = (self.dict.objectForKey("last_name") as? String)!
Uerextra.avatarUrl = self.dict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as! String
Uerextra.FacebookId = (self.dict.objectForKey("id") as? String)!
Uerextra.saveWithCompletionBlock { error in
if error != nil {
print(error)
}
}
}
And I need 1 extra field with reference to user id.
This is my class:
class userextra : SCDataObject {
var name = ""
var lastName = ""
var avatarUrl = ""
var FacebookId = ""
var user: SCUserProfile! = nil
}
Ok after several attempts I managed to save this reference to Syncano.
This is my code:
func saveName() {
user_profile.please().enumaratePagesWithPredicate(nil, parameters: [SCPleaseParameterPageSize : 25]) {shouldStop, s_data, error in
guard error == nil else {
return
}
if let s_data = s_data as? [user_profile] {
for user in s_data {
let uzytkownik = user
let Uerextra = userextra()
Uerextra.name = (self.dict.objectForKey("first_name") as? String)!
Uerextra.lastName = (self.dict.objectForKey("last_name") as? String)!
Uerextra.avatarUrl = self.dict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as! String
Uerextra.FacebookId = (self.dict.objectForKey("id") as? String)!
Uerextra.user = uzytkownik
Uerextra.saveWithCompletionBlock { error in
if error != nil {
print(error)
}
}
}
}
}
}
and user_profile class:
class user_profile: SCUserProfile {
var id = 0
var Name = ""
var Surename = ""
}
Most important is register class in app delegate
SCUser.registerClassWithProfileClass(userextra.self)
SCUser.registerClassWithProfileClass(user_profile.self)