自动后台通知firebase数据库

时间:2016-12-17 12:39:13

标签: android swift firebase push-notification firebase-realtime-database


我为我的学校开发了一个应用程序,其中一个功能是校长的更新。为此,我正在使用Firebase实时数据库。我需要在添加新的孩子(消息)时应用程序自动发送通知(背景)。

这是我的阅读代码(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)

}

这是我的写代码(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)

}

这是我的读代码(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) {
        }
    });
}

这是我的写代码(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);


        }
    });
}

我应该在代码中创建或更改内容(如果可以的话,适用于iOS和Android) 我最近购买了Apple Developer Program会员资格,很快就会被激活。

感谢帮助者。

1 个答案:

答案 0 :(得分:0)

所以,经过很长一段时间我一直在寻找解决方案之后,我发现了一种非常简单的方法,它就是使用云套件。这是布莱恩出现的教程:

https://youtu.be/BXl5o5_2aEU
我建议你去看他的第一个视频:https://youtu.be/XQ3nLV2778U,然后做一些这样的事情。

编辑:2017

现在,我们可以使用Firebase云功能,以便在数据库发生变化时发送推送通知。