gpt4 book ai didi

ios - 如何使用 Alamofire Swift 3 返回响应结果以发挥作用

转载 作者:行者123 更新时间:2023-11-28 21:05:29 25 4
gpt4 key购买 nike

我使用 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")
}
}

}

Running result

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com