作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用 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 和网络编程的初学者,我用谷歌搜索并看到了 Swift 文档,不知道如何解决这个问题。任何人都可以提供帮助吗?非常感谢。
最佳答案
您没有使用闭包,这就是 getLastModifiedDate
返回 nil 的原因,因为它没有返回 "Last-Modified"
值。如果您正在执行异步任务,则必须使用闭包这个
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)
}
}
关于ios - 如何使用 Alamofire Swift 3 返回响应结果以发挥作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45902612/
在 Play 1.x 中有很棒的 play Idealize(和 play eclipsify),它为您最喜欢的 IDE 中的 Play 项目准备了项目文件。 我看到这是在 Play 2.X 中删除的
我是一名优秀的程序员,十分优秀!