2

Long time reader, first time asker.
I have an app that sends JSON messages when a condition occurs. I'm trying to get the webpage to refresh when it receives the JSON message.
I'm very new to web development and used this great tutorial to get the Get Post going: https://www.youtube.com/watch?v=aTj0ZLha1zE

I used https://stackoverflow.com/users/88204/james-lawruk great answer here to refresh the webpage when the local file "data.json" is changed. How to refresh a page whenever my json data file changes

What I can't figure out is how to trigger the refresh from swift. I'm probably missing something fundamental here but i'm not sure where to look.

My swift code:

@IBAction func OnPostTapped(_ sender: Any) {
    let parameters = ["username": "@you", "tweet": "HelloWorld"]
    guard let url = URL(string: "http://localhost:8888/data.json") else { return }
    var request = URLRequest(url:url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {return }
    request.httpBody = httpBody
    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in 
    if let response = response {
         print (response)
    }
    if let data = data {
    do {
         let json = try JSONSerialization.jsonObject(with: data, options: [])
         print (json)
    }catch {
        print (error)
            }
        }
    }.resume()
}

Edit

I should have clarified, the app doesn't have a UIWebView, it just sends JSON to a webpage. I'm trying to get the webpage to refresh on the user's browser.

udipilot
  • 21
  • 3
  • You should be executing `yourWebView.reload();` – gotnull Aug 02 '18 at 03:54
  • What you're trying to achieve doesn't make any sense? There would be no way to refresh a webpage on the user's browser unless your application controls the browser. (`UIWebView` in this case). – gotnull Aug 02 '18 at 05:09
  • Your web browser could poll the server for updates. That would have nothing to do with swift or any kind of direct link with your app posting new data, it would be a separate mechanism. – James Aug 02 '18 at 05:18

2 Answers2

1

I'm going to assume you're inside a UIWebView.

If this is the case then you can execute webView.reload(); to refresh the page.

gotnull
  • 26,454
  • 22
  • 137
  • 203
0

Turns out what I was trying to do was impossible. I ended up creating a mySql database to which the app adds data. The webpage keeps looking at the database to see if there are changes and prints out the newest one. There are probably cleaner ways to do it but it's working. If anyone is interested in my code let me know and I'll add it. Thanks again for the help.

udipilot
  • 21
  • 3