MuMtaZ MuMtaZ -4 years ago 77
Swift Question

How to send messages notifications in iOS?

I am searching for an hour for a way to do that(without Parse because it's going down this month).

I am trying to do in the app that one user can send push notification message to another specific user.

What are the options to implement that?(please be specific)

Thanks.

Answer Source

What you're looking for is not typically recommended, as it can very easily become problematic. Techincally, users should not be able to send direct push notifications to other users. All notifications should be handled through a central system that wouldn't be accessible to your individual users. However, if you feel that you'd still like to make this work, read on.

I have a mechanism like this in one of my apps, using FCM. Here's the function (with some modifications to take out my specific information) that I use to send messages from one user to another:

func push(message: String, toUser: String) {
    var token: String?
    for person in self.users {
        if toUser == person.username && person.firebaseToken != nil {
            token = person.firebaseToken
        }
    }
    if token != nil {
        var request = URLRequest(url: URL(string: "https://fcm.googleapis.com/fcm/send")!)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("key=[your FCM Server Key]", forHTTPHeaderField: "Authorization")
        let json = [
            "to" : token!,
            "priority" : "high",
            "notification" : [
                "body" : message
            ]
        ] as [String : Any]
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
            request.httpBody = jsonData
            let task = URLSession.shared.dataTask(with: request) { data, response, error in
                guard let data = data, error == nil else {
                    print("Error=\(error)")
                    return
                }

                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
                    // check for http errors
                    print("Status Code should be 200, but is \(httpStatus.statusCode)")
                    print("Response = \(response)")
                }

                let responseString = String(data: data, encoding: .utf8)
                print("responseString = \(responseString)")
            }
            task.resume()
        }
        catch {
            print(error)
        }
    }
}

I keep this method in my appDelegate, and call it whenever necessary. Basically, every user in my app has a Firebase messaging token assigned to them, and it's just another property of each user. You can get a user's FCM token with this call:

let token = FIRInstanceID.instanceID().token()

Usually, the token can be retrieved and saved when a user first creates an account. The token will remain the same as long as the user uses the same device.

Again, this can be very dangerous if it is implemented without proper security measures to prevent your users from having total control over sending push notifications.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download