簡體   English   中英

Swift / Alamofire完成處理程序的難度

[英]Difficulty with Swift/Alamofire Completion Handlers

今天,我正在使用Alamofire提取int值。 它將int拉得很好,但是我想將int值保存在請求之外(在另一個函數中,viewDidLoad())。

我不確定如何調用完成處理程序,目前似乎什么也沒做。

這是提取有問題的int值的方法(lastModified)。

func checkVersion(completion: @escaping (Int) -> Void) {
    Alamofire.request(versionCheckEndpoint).responseJSON { response in
        if(response.result.value != nil) {
            let json = JSON(response.result.value!)
            self.s3Endpoint = json["s3BucketURL"].stringValue
            let lastModified = json["lastModified"].intValue
            self.latestVersion = lastModified
        }
    }
}

我嘗試將值保存到實例變量,但這不起作用。

我在viewDidLoad()中這樣稱呼完成處理程序,但是我很肯定,它遠不正確:

 self.checkVersion() { response in
        self.latestVersion = response
    }

誰能給我一些見識,以了解如何將lastModified的int值保存到某些局部變量中,從而使其不包含在Alamofire請求的范圍內?

checkVersion函數中,未調用完成塊。

您必須在獲取值后調用它(盡管我建議將其設置為可選)

func checkVersion(_ completion: @escaping (Int?) -> Void) {
    Alamofire.request(versionCheckEndpoint).responseJSON { response in

        guard let value = response.result.value else {
            completion(nil)
            return
        }

        let json = JSON(value)
        self.s3Endpoint = json["s3BucketURL"].stringValue
        let lastModified = json["lastModified"].intValue

        completion(lastModified)
    }
}

並這樣稱呼它:

self.checkVersion() { value in

    guard let value = value else {
        //handle invalid values here
        return
    }

    latestVersion = value
    // update the view if needed
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM