Stephen Tam Stephen Tam - 2 months ago 20
iOS Question

How to return respond result to function with Alamofire Swift 3

I use Alamofire framework for doing read server json file and download it. I want to check the json last modified date and let user decieded to download json contents. But the function getLastModifiedDate always return nil. I list the sample code here.

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

I am beginner of Swift 3 and network progamming, I google and saw Swift document no idea how to resolve this problem. Anyone can give help? Thank you very much.

Answer Source

You are not using closures that's why getLastModifiedDate returns nil because it's not returning "Last-Modified" value .You have to use closures if you are doing async task like this

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)

    }

}