Firebase Database not Uploading - ios

I have my upload code here
import UIKit
import Firebase
class ChatViewController: UIViewController {
let chatRef = FIRDatabase.database().reference().child("chat")
let userUid = FIRAuth.auth()?.currentUser?.uid
var userName = ""
#IBOutlet weak var topBar: UINavigationItem!
#IBOutlet weak var containerView: UIView!
#IBOutlet var inputTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
topBar.title = "Chat Log Controller"
FIRDatabase.database().reference().child("users/\(userUid!)/name").observe(.value) { (snap: FIRDataSnapshot) in
self.userName = (snap.value! as! String).description
}
}
#IBAction func handleSend(_ sender: AnyObject) {
let childChatRef = chatRef.childByAutoId()
let message = inputTextField.text!
childChatRef.child("text").setValue(message)
print(inputTextField.text)
}
#IBAction func handleSendByEnter(_ sender: AnyObject) {
let childChatRef = chatRef.childByAutoId()
let message = inputTextField.text!
print(userName)
childChatRef.child("name").setValue(userName)
childChatRef.child("text").setValue(message)
print(inputTextField.text)
}
}
text is successfully uploaded But
It doesn't print userName and doesn't upload it to Firebase Database
But username is nut nil!

Try to use your observer code as,
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
}

Just take self.username = snap.value! as! String
It will solve your problem.

Related

How to update data in the firebase using swift?

I have made an sign up and also login and it works! but now I want to edit the data in the Firebase. Can anyone help me how to do it? Thanks you
Here the Sign Up View Controller
import UIKit
import FirebaseAuth
import FirebaseFirestore
class SignupViewController: UIViewController {
#IBOutlet weak var FirstNameTextfield: UITextField!
#IBOutlet weak var LastNameTextfield: UITextField!
#IBOutlet weak var EmailTextField: UITextField!
#IBOutlet weak var PasswordTextfield: UITextField!
#IBOutlet weak var SignUpButton: UIButton!
#IBOutlet weak var ErrorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setUpElements()
}
func setUpElements(){
ErrorLabel.alpha = 0
}
func validateFields()->String? {
//check that all the fields are fill
if FirstNameTextfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || LastNameTextfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || EmailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || PasswordTextfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == ""
{
return "Please fill up all the Fields"
}
//check the password if the password is secure
let cleanedPassword = PasswordTextfield.text!.trimmingCharacters(in: .whitespacesAndNewlines)
if Utilities.isPasswordValid(cleanedPassword) == false{
return "Please enter at least 8 characters, with a number and characteristic symbol"
}
return nil
}
#IBAction func SignUpTap(_ sender: Any) {
let error = validateFields()
if error != nil{
showError(message: error!)
}
else {
let FirstName = FirstNameTextfield.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let LastName = LastNameTextfield.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Email = EmailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Password = PasswordTextfield.text!.trimmingCharacters(in: .whitespacesAndNewlines)
Auth.auth().createUser(withEmail: Email, password: Password) { (result, err) in
if err != nil{
self.showError(message: "Error creating the user")
}
else {
let db = Firestore.firestore()
db.collection("users").addDocument(data:["FirstName":FirstName, "LastName":LastName, "uid": result!.user.uid]) { (Error) in
if error != nil{
self.showError(message: "Cannot saving user data" )
}
}
self.transitionToHomePage()
}
}
}
}
func showError( message:String){
ErrorLabel.text = message
ErrorLabel.alpha = 1
}
func transitionToHomePage(){
let TabHomeViewController = storyboard?.instantiateViewController(identifier: Constrants.Storyboard.TabHomeViewController) as? TabHomeViewController
view.window?.rootViewController = TabHomeViewController
view.window?.makeKeyAndVisible()
}
}
Here my login VC
#IBAction func LoginTap(_ sender: Any) {
let Email = EmailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Password = PasswordTextfield.text!.trimmingCharacters(in: .whitespacesAndNewlines)
Auth.auth().signIn(withEmail: Email, password: Password) { (result, error) in
if error != nil{
self.ErrorLabel.text = error!.localizedDescription
self.ErrorLabel.alpha = 1
}
else{
let TabHomeViewController = self.storyboard?.instantiateViewController(identifier: Constrants.Storyboard.TabHomeViewController) as? UITabBarController
self.view.window?.rootViewController = TabHomeViewController
self.view.window?.makeKeyAndVisible()
}
And here my Account View Controller
import UIKit
import FirebaseAuth
import FirebaseFirestore
import Firebase
class AccountViewController: UIViewController {
#IBOutlet weak var FNameTextField: UITextField!
#IBOutlet weak var LNameTextField: UITextField!
#IBOutlet weak var EmailTextField: UITextField!
#IBOutlet weak var PasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func logoutbutton(_ sender: Any) {
do{
try Auth.auth().signOut()
performSegue(withIdentifier: "signout", sender: nil)
}
catch{
print(error)
}
}
}
You can use this function:
func updateFirestoreUserProfile(uid: String, data: [String:Any]) {
Firestore.firestore().collection("users").document(uid).updateData(data) { err in
if let err = err {
print("Error updating document: \(err) ")
}
else {
print("Document successfully updated")
}
}
}
You can use the function like this:
let data = [
"FirstName": name,
"LastName": surname
]
updateFirestoreUserProfile(uid: user.uid, data: data)

TableViewCell pass data to ViewController (Parse.com)?

Tell me what can be a mistake. I have 6 columns, two columns belong to TableViewCell. The other 4 belong to the ViewController. How do I tie the rows correctly so that the match information matches its row in TableViewCell.
import UIKit
import Parse
class DetailTennisViewController: UIViewController {
#IBOutlet weak var imageTennis: UIImageView!
#IBOutlet weak var outClose: UIButton!
#IBOutlet weak var titleTennis: UILabel!
#IBOutlet weak var textTennis: UITextView!
#IBOutlet weak var progTennis: UILabel!
#IBAction func closeOut(_ sender: Any) {
dismiss(animated: false, completion: nil)
}
var tenises : Tennis?
func configureButton() {
outClose.layer.cornerRadius = 0.5 * outClose.bounds.size.width
outClose.clipsToBounds = true
}
override func viewDidLoad() {
super.viewDidLoad()
loadTennis()
configureButton()
}
func loadTennis () {
let qwery = PFQuery(className: "tennis")
qwery.getFirstObjectInBackground() { (object,error) ->Void in
if error == nil {
self.textTennis.text = object!["textTen"] as? String
self.progTennis.text = object!["progTen"] as? String
self.titleTennis.text = object!["titleTen"] as? String
let imageFile = object!["tenImage"] as? PFFile
imageFile?.getDataInBackground() { (data:Data?, error:Error?)->Void in
if error == nil {
if let imageData = data {
self.imageTennis.image = UIImage(data: imageData)
}
}
}
}
}
}
}
How to make the data string Parse.com How to make the data TableViewCell cells corresponded to the description ViewController. In my code, when the cell is opened, the same data is displayed. I uploaded 4 events and information about them. So the information about them opens up the same. How to make the one that is indicated by their "objectId"

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

how to pass data from firebase between tableview cell to view controllers?

Hi guys I'm really having troubles trying to pass data from a tableview to another view controller. I have a tableview that displays a list of every user but when I click on a user it goes to the next view controller without showing any data of that particular user. The code below is pretty much the same from an example I followed but for some reason its not working for me. Please help, I've tried searching for solutions but can't find anything. Im also using firebase to store and retrieve my data. Thanks in advance
#IBOutlet weak var searchTableView: UITableView!
var profiles = [user]()
var ref: FIRDatabaseReference!
override func viewdidload(){
databaseRef = FIRDatabase.database().reference()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "guestSegue", sender: self)
self.searchTableView.deselectRow(at: indexPath as IndexPath, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "guestSegue" {
if let indexpath = searchTableView.indexPathForSelectedRow {
let guestVC = segue.destination as! guestProfileViewController
guestVC.ref = profiles[indexpath.row].ref
}
}
}
user array
class User {
var backgroundProfileImage: String!
var fullName: String!
var profilePic: String!
var ref: FIRDatabaseReference!
var key: String
init(backgroundProfileImage: String, fullName: String, profilePic: String, key: String = ""){
self.backgroundProfileImage = backgroundProfileImage
self.fullName = fullName
self.profilePic = profilePic
self.key = key
self.ref = FIRDatabase.database().reference()
}
init(snapshot: FIRDataSnapshot){
self.backgroundProfileImage = value["backgroundProfileImage"] as! String!
self.fullName = (snapshot.value as! NSDictionary)["fullName"] as! String
self.profilePic = (snapshot.value as! NSDictionary)["profilePic"] as! String
self.uid = (snapshot.value as! NSDictionary)["uid"] as! String!
self.key = snapshot.key
self.ref = snapshot.ref
}
guestViewController
class guestProfileViewController: UIViewController, UINavigationControllerDelegate {
#IBOutlet weak var profileImage: UIImage!
#IBOutlet weak var backgroundProfileImage: UIImageView!
#IBOutlet weak var fullNameLabel: UILabel!
var ref: FIRDatabaseReference?
override func viewDidLoad() {
super.viewDidLoad()
ref = FIRDatabase.database().reference()
loadProfileData()
}
func loadProfileData(){
if let ref = ref {
ref.observe(.value, with: { (user) in
let user: User = User(snapshot: user)
self.fullNameLabel.text = user.fullName
self.profileImage.sd_setImage(with: URL(string: user.profilePic), placeholderImage: UIImage(named: "default"))
self.backgroundProfileImage.sd_setImage(with: URL(string: user.backgroundProfileImage), placeholderImage: UIImage(named: "default_1"))
})
}
}
}
ref is being set in viewDidLoad() of guestProfileViewController. Try removing that bit as it seems like you want ref to equal the User's ref.

Data persistence after call to webservice iOS

Sorry for my English.
I have many problems in achieving data persistence after call the webservice .
Everything works correctly but I need to use that data in other methods .
As seen in the image once charge data on the screen then I want to give the user the option to use them well or load new data . But not as saving the data recovery webservice .
I was trying to use NSUserDefault but neither work .
From already thank you very much , any response is helpful .
Regards!
ViewController:
class ViewController: UIViewController {
let defaults = NSUserDefaults.standardUserDefaults()
#IBOutlet weak var myLabel2: UITextField!
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.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let newVC : SecondViewController = segue.destinationViewController as! SecondViewController
let telefono = myLabel2.text!
newVC.recibirString = telefono
}
#IBAction func mostrarAlgo(sender:AnyObject) {
//something
}
}
SecondViewController:
class SecondViewController: UIViewController {
let defaults = NSUserDefaults.standardUserDefaults()
var tel: String = ""
#IBOutlet weak var myLabel1: UITextField!
#IBOutlet weak var myLabel3: UITextField!
#IBOutlet weak var myLabel4: UITextField!
#IBOutlet weak var myLabel5: UITextField!
#IBOutlet weak var myLabel6: UITextField!
#IBOutlet weak var myLabel7: UITextField!
#IBOutlet weak var myLabel8: UITextField!
var recibirString = String()
override func viewDidLoad() {
super.viewDidLoad()
myLabel1.text = recibirString
performRequestAndUpdateUI2(myLabel1.text!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func performRequestAndUpdateUI2(tel:String) {
WebService.llamarWebService (tel,completionHandler: { datos in
guard datos.count == 5 else {
self.myLabel8.text = ("El número ingresado no está registrado.")
return
}
guard datos[0] as! String == "OK" else {
print("not everything was OK")
return
}
dispatch_async(dispatch_get_main_queue()) {
self.myLabel3.text = datos[0] as? String
self.myLabel4.text = datos[1] as? String
self.myLabel5.text = datos[2] as? String
self.myLabel6.text = datos[3] as? String
self.myLabel7.text = datos[4] as? String
self.myLabel8.text = ("Usted está registrado.")
//need save this data
}
})
}
#IBAction func guardarDatos(sender: AnyObject) {
// do something
}
}
WebService:
class WebService{
var telefono = ""
class func llamarWebService(telefono:String, completionHandler: (datos:NSArray)->()){
let urlPath = "http://xxxxxxxxxxx.com.ar/xxxxxxxxxx/forwarder_number?phone=\(telefono)"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
var arreglo:NSArray!
let task = session.dataTaskWithURL(url!,completionHandler: {data,response,error -> Void in
if (error != nil){
print(error?.localizedDescription)
}
let nsdata: NSData = NSData(data: data!)
arreglo = self.retornarDatos(nsdata)
completionHandler(datos: arreglo)
})
task.resume()
}
class func retornarDatos(nsdata: NSData)-> Array<String>{
let datos = NSString(data:nsdata,encoding: NSUTF8StringEncoding)
let partes = datos?.componentsSeparatedByString(",")
var arreglo : [String] = []
for i in partes!{
arreglo.append(i)
}
return arreglo
}
}

Resources