我使用 Alamofire 框架来读取服务器 json 文件并下载它。我想检查 json 上次修改日期并让用户决定下载 json 内容。但是函数 getLastModifiedDate 总是返回 nil。我在这里列出了示例代码。
import Foundation
import UIKit
import Alamofire
class ViewController: UIViewController {
@IBOutlet var lastModifedDateLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if (getLastModifiedDate() != nil) {
let alertController = UIAlertController(title: "Information", message: "Download or NOT", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "NO", style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: "YES", style: .default, handler: {action in
self.callDownload()
}))
self.present(alertController, animated: true, completion: nil)
}
}
func getLastModifiedDate() -> String? {
var date:String?
Alamofire.request("http://www.example.com/apps/demopad/manifest.json")
.response { serverResponse in
date = serverResponse.response?.allHeaderFields["Last-Modified"] as? String
print(date ?? "Server date is nil")
self.lastModifedDateLabel.text = date
}
return date
}
func callDownload() {
print("Call Download func")
Alamofire.request("http://www.example.com/apps/demopad/manifest.json")
.responseJSON { serverRespone in
let jsonDict = serverRespone.result.value as? Dictionary<String, Any>
print(jsonDict ?? "JSON data is nil")
}
}
}
我是 Swift 3 和网络编程的初学者,我 google 并看到 Swift 文档不知道如何解决这个问题。任何人都可以提供帮助吗?非常感谢你。
您没有使用闭包,这就是getLastModifiedDate
返回 nil 的原因,因为它没有返回"Last-Modified"
value 。如果您正在执行这样的异步任务,则必须使用闭包
func getLastModifiedDate(completion: @escaping (String) -> ()) {
var date:String?
Alamofire.request("http://www.example.com/apps/demopad/manifest.json")
.response { serverResponse in
date = serverResponse.response?.allHeaderFields["Last-Modified"] as? String
print(date ?? "Server date is nil")
self.lastModifedDateLabel.text = date
completion(date)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句