0

I am trying to implement a method so that critical messages are logged inside of a MySQL database.

It is critical that after these messages are generated by the application the application continues to try and send the message until it has reached the database successfully. (The user may be offline or something else unexpected may happen)

However the database should not receive the same message twice.

Logging is important because the user may generate these error messages while offline or they might not successfully get onto the database.

I am attempting to do this using NSUserDefaults assuming that I can store each request in a persistent array and remove elements once they have been successfully sent.

My first design was this:

private static let defaults = UserDefaults.standard
private static let backupQueue = "Messages"
public  static func log(message: String) {

    var messageArray:[String] = [String]()

    if (defaults.value(forKey: backupQueue) as? [String] == nil) {
        defaults.set(messageArray, forKey: backupQueue)
    }
    messageArray = defaults.value(forKey: backupQueue) as! [String]

    messageArray.append(message)

    for i in (0..<messageArray.count).reversed() {
        let result = sendOff(message: messageArray[i])
        if (result) {
            messageArray.remove(at: i)
        }
    }

    defaults.set(messageArray, forKey: backupQueue)

}
private static func sendOff(message: String) -> Bool {
    return //Return true if it was sent and false if it was not
}

It works perfectly with one huge oversight. Any sort of web request from an app is supposed to be handled asynchronously so obviously we cant generate a true or false value immediately.

Additionally I cannot even figure out how exactly to format the POST request. For example I know if I go to my web browser and put http://coolSite.org/Debug.php?message="We have a problem" as the address it will successfully post a message to my database. However when I try doing a technique like this to request the html from a site it doesn't work. I don't tend to get any error messages back until about 40 seconds after sending the requests.

Therefore I have 2 problems:

  1. How am I supposed to handle the removing of elements from NSUserDefaults once they have been sent if I cannot guarantee what order I will receive confirmation of their receipt in since it is asynchronous.
  2. I cannot get Swift to properly go to a URL in the same way it does in a web browser.
Shadow
  • 33,525
  • 10
  • 51
  • 64
J.Doe
  • 1,502
  • 13
  • 47

0 Answers0