Fast REST feedback for fast iOS performance

My Swift iOS App communicates with a REST web service to receive JSON data. When finished, it will update the UITableView with the appropriate UITableViewController.

To keep this clean, I created a new swift file and placed the request code there.

Interface.swift

import Foundation
class WTInterface {

func login() -> Bool {
    var token: String?
    println("login. initializing request...")
    var url = NSURL(string: "https://report.somewebservice/data.cgi")
    var request = NSMutableURLRequest(URL: url!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"
    var params = [:]

    var requestBody = [
        "method" : "login",
        "params" : [
            "customerId": "235879840188032",
            "login": "foobar",
            "pass": "somepassowrd",
            "language": "en"
        ],
        "version" : "1.1"
    ]
    var err: NSError?
    request.HTTPBody = NSJSONSeri...............

      

ViewController

import UIKit

class ViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


    var wtinterface = WTInterface()


    wtinterface.login()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

      

The question is what is the best way to update my UITableView since this is an asynchronous request. I've read a lot about callbacks and closures and older blog posts and answers, but I haven't found a good answer for this. (Mainly because I believe the strategies are already outdated ...)

Can anyone point me in the right direction and paste in some sample code?

+3


source to share


1 answer


Maybe helpful for someone a little time down the road:

A closure is used in response. Note that this @escaping

indicates that the closure is escaped, meaning it is not "just fired", but might, for example, wait for something asynchronous like a network request. Note that when using these options, the UI cannot be updated inside these (as they don't work on the middle thread), instead schedule something for the main thread to do this.



func myClosure(callback: @escaping (_ greeting: String?) -> Void) {
  print("lalalala")
  // Do async request stuff here
  callback("Hi there!")
}

myClosure() { aGreeting in
  guard aGreeting != nil else {
    return
  }
  print(aGreeting!)
}

      

0


source







All Articles