【问题标题】:How to return respond result to function with Alamofire Swift 3如何使用 Alamofire Swift 3 将响应结果返回给函数
【发布时间】:2018-02-04 18:08:49
【问题描述】:

我使用 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 和网络编程的初学者,我 google 并看到 Swift 文档不知道如何解决这个问题。任何人都可以提供帮助吗?非常感谢。

【问题讨论】:

  • 闭包的返回类型为 void。您不能从关闭中返回,请改用完成处理程序。

标签: ios swift3 alamofire


【解决方案1】:

试试这个代码

 func getLastModifiedDate() -> String? {

    var date:String?

    Alamofire.request("http://www.example.com/apps/demopad/manifest.json")
        .response {
            switch response.result {
            case .success(let JSON):
                print("Success with JSON: \(JSON)")
                print("Request failed with error: \(response.response?.statusCode)")

                if let response = JSON as? NSMutableDictionary
                {

                    date = response?.object(forKey: "Last-Modified") as! String

                    print(date ?? "Server date is nil")
                    self.lastModifedDateLabel.text = date
                }
                else if let response = JSON as? NSDictionary
                {

                    date = response?.object(forKey: "Last-Modified") as! String

                    print(date ?? "Server date is nil")
                    self.lastModifedDateLabel.text = date
                }
                else if JSON is NSArray
                {

                }

                break

            case .failure(let error):
                print("Request failed with error: \(error)")
                callback(response.result.value as? NSMutableDictionary,error as NSError?)
                break
            }


        }
        .responseString { response in

            print("Response String: \(response.result.value)")
    }
 }
 return date
 }

【讨论】:

    【解决方案2】:

    您没有使用闭包,这就是 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)
    
        }
    
    }
    

    【讨论】:

    • 因为我想提示alert view,用户点击OK,我会调用一个下载json(callDowload)函数。我计划 callDownload 也会有返回值,是否也在 callDownload() 中使用闭包?我可以不使用异步模式等待服务器返回,然后执行下一步吗?我的概念错了吗?
    • 看,调用下载正在执行服务器调用,因此您必须等待它,因此您必须使用完成处理程序来等待响应。因此,如果您执行服务器调用,那么您必须使用闭包。希望你得到了吗?
    猜你喜欢
    • 2018-06-29
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    相关资源
    最近更新 更多