Alamofireフレームワークを使用して、読み取りサーバーjsonファイルを作成し、ダウンロードします。私は、JSONの最終更新日を確認して、ユーザーにjsonのコンテンツをダウンロードさせたいと思っています。しかし、関数getLastModifiedDateは常にnilを返します。ここにサンプルコードを記載します。Alamofire Swift 3を使用して応答結果を返す方法
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")
}
}
}
私はスウィフト3の初心者やネットワークprogamming午前、私はこの問題を解決する方法は考えてグーグルないとスウィフト文書を見ました。誰でも助けてもらえますか?どうもありがとうございました。
を試してみてくださいクロージャを使用する必要がありますなぜ
getLastModifiedDate
戻りはnilクロージャを使用していませんクロージャの戻り値の型はvoidです。クロージャから戻ってくることはできません、代わりに完了ハンドラを使用してください。 –