0

我有一个从网站 api 获取数据的函数。

func getData() {
print("getData is called")
//create authentication ... omitted

//create authentication url and request
let urlPath = "https://...";
let url = NSURL(string: urlPath)!
let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
request.HTTPMethod = "GET"

//some configuration here...

let task = session.dataTaskWithURL(url) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
    let json = JSON(data: data!)
}
    task.resume()
}

我能够从 API 获取数据,并且我有一个观察者,因此每次当应用程序进入前台时,都可以再次调用 getData() 函数来更新数据。

override func viewDidLoad() {
     NSNotificationCenter.defaultCenter().addObserver(self, selector: "willEnterForeground", name: UIApplicationWillEnterForegroundNotification, object: nil)
}

func willEnterForeground() {
     print("will enter foreground")
     getData()
}

我很确定当我的应用程序进入前台时,会再次调用 getData(),但是,即使服务器 API 上的数据发生更改,我的数据也不会更新。我试图关闭应用程序并再次打开它,但它仍然没有更新数据。所以我想知道是否有人可以给我一些建议。任何帮助将不胜感激!

4

2 回答 2

0

你需要 a 使它成为一个完成的闭包。这将使它能够发出请求,然后在您实际从请求中取回数据后调用 reload "Table View"。这是您需要更改 getData()功能的内容

func getData(completion: (json) -> Void)) {
     print("getData is called")
     //create authentication url and request
     let urlPath = "https://...";
     let url = NSURL(string: urlPath)!
     let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
     request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
     request.HTTPMethod = "GET"

     //some configuration here...

     let task = session.dataTaskWithURL(url) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
           let json = JSON(data: data!)
     }
       completion(json)
}

然后您将需要调整调用此函数的位置,因为您已经更改了参数,它应该看起来更像这样。

func willEnterForeground() {
    print("will enter foreground")

    getData(completion:{
        self.data = json
        self.tableView.reloadData()
    })
}

这将等到数据返回,然后重新加载视图,更新所有内容以反映服务器上的内容。

如果您有更多问题,请告诉我。

于 2016-02-14T23:52:04.433 回答
0

我终于发现这是因为我没有删除缓存。然后更改缓存策略。

于 2016-02-16T00:59:08.683 回答