3


I developed an application to my school and one of the features is principal's updates. For this, I'm using the Firebase realtime database. I need that the app will send automatically notification(background) when a new child(message) is added.

this is my read code(swift):

var messages = [Message]()

override func viewDidLoad() {
    super.viewDidLoad()

    observeMessages()
}

func observeMessages() {
    let dbRef = FIRDatabase.database().reference().child("messageS")
    dbRef.observe(.childAdded, with: { (snapshot) in

        if let dictionary = snapshot.value as? [String: AnyObject] {
            let text = Message()
            text.setValuesForKeys(dictionary)
            self.messages.insert(text, at: 0)


            DispatchQueue.main.async(execute: {
                self.tableView.reloadData()
            })
        }

        }, withCancel: nil)
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return messages.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellId")

    let message = messages[indexPath.row]
    cell.textLabel?.text = message.title
    cell.textLabel?.textAlignment = .center
    cell.detailTextLabel?.text = message.message
    cell.detailTextLabel?.textAlignment = .right

    // Configure the cell...

    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


    let message = messages[indexPath.row]
    let title = message.title
    let msg = message.message
    let controller = UIAlertController(title: title, message: msg, preferredStyle: .alert)
    let cancelAction = UIAlertAction(title: "סגור", style: .cancel) { (handler) in
        // Any action when you cancel
    }
    controller.addAction(cancelAction)
    self.present(controller, animated: true, completion: nil)

}

this is my write code(swift):

@IBOutlet weak var MessageTitle: UITextField!
@IBOutlet weak var MessageText: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

func post() {
    let title: String = MessageTitle.text!
    let message: String = MessageText.text!

    let post: [String: AnyObject] = ["title": title as AnyObject,
                                    "message": message as AnyObject]
    let dbRef = FIRDatabase.database().reference()
    dbRef.child("messageS").childByAutoId().setValue(post)



}
@IBAction func Publish(_ sender: AnyObject) {
    post()



    let MessageSent = UIAlertController(title: "נשלח", message: "ההודעה נשלחה בהצלחה", preferredStyle: UIAlertControllerStyle.alert)
    MessageSent.addAction(UIAlertAction(title: "תודה", style: UIAlertActionStyle.default, handler: nil))
    self.present(MessageSent, animated: true, completion: nil)

}

this is my read code(android):

private Firebase mRef;
public ArrayList<String> messages = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_updates);

    mRef = new Firebase("https://ksharet-d6a24.firebaseio.com");
    mRef.child("messageS");
    // Get ListView object from xml
    final ListView listView = (ListView) findViewById(R.id.ListView);

    // Create a new Adapter
    final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
            android.R.layout.simple_list_item_1, messages);

    // Assign adapter to ListView
    listView.setAdapter(adapter);


    mRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                Message message = postSnapshot.getValue(Message.class);
                messages.add(0, message.getTitle() + '\n' + message.getMessage());
            }
            adapter.notifyDataSetChanged();

        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
        }
    });
}

this is my write code(android):

private Button sendData;
private Firebase mRef;
private EditText messageBox = (EditText) findViewById(R.id.MessageText);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_publish);

    Firebase.setAndroidContext(this);

    mRef = new Firebase("https://ksharet-d6a24.firebaseio.com/");
    mRef.child("message");
    sendData = (Button) findViewById(R.id.sendMessage);

    sendData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String message = messageBox.getText().toString();
            //Firebase mRefChild = mRef.child("message");
            //mRefChild.setValue(message);
            mRef.push().setValue(message);


        }
    });
}

what should I create or change in the code(if you can, for both iOS and Android).
I recently purchased the Apple Developer Program membership and It'll probably be activated soon.

thanks for the helpers.

A. Inbar
  • 80
  • 14
  • What is the actual issue your running into? – shallowThought Dec 17 '16 at 14:12
  • @shallowThought I want to do automatically push notifications on the background when new message is arrived to the database. – A. Inbar Dec 17 '16 at 15:11
  • Maybe helpful: http://stackoverflow.com/questions/25078953/does-firebase-handle-push-notifications – shallowThought Dec 17 '16 at 15:25
  • @shallowThought I want the application will send it automatically and not manually through the console – A. Inbar Dec 17 '16 at 15:29
  • As far as I know it is not possible to send Notifications on data change with firebase. If I am right, you need additional tools. Maybe one of the ones mentioned in the thread I pointed to. Good luck. – shallowThought Dec 17 '16 at 15:34
  • I can't find. can someone guide me? I don't care to use external tool (It should be like chat app notification) – A. Inbar Dec 17 '16 at 16:17

1 Answers1

0

so, after a lot of time that I've been searching for solutions, I found a really easy way to do it, and it is by using cloud kit. that's the brian advent's tutorial:

https://youtu.be/BXl5o5_2aEU
I suggest you to go to his first video: https://youtu.be/XQ3nLV2778U and just do few of those things.

EDIT: 2017

Now we can use Firebase cloud functions in order to send a push notification when the database changes.

A. Inbar
  • 80
  • 14