获取当前月份和年份并传递给 API iOS Swift?

anu*_*nuj 0 api json ios swift3

我有一个 func,我必须在其中将当前月份和年份参数传递给 Swift 3 中的 Fetch API。代码 :-

func raffleNumberGenerate(){
    let prs = [
        "month":currentMonth,
        "year" : currentYear,
        "raffle_result": "1" as String
    ]
    Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion: { result in
        let jsonResponseSingle = result as? NSDictionary
        print(" JSON Response :- \(String(describing: jsonResponseSingle))"
}
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Cod*_*nja 6

您没有currentMonthand 的值currentYear,因此您必须创建一些值。

func raffleNumberGenerate() {
    let date = Date() // gets current date
    let calendar = Calendar.current
    let currentYear = calendar.component(.year, from: date) // gets current year (i.e. 2017)
    let currentMonth = calendar.component(.month, from: date) // gets current month (i.e. 10)

    let prs = [
        "month":currentMonth,
        "year" : currentYear,
        "raffle_result": "1" as String
    ]

    Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion: { result in
        let jsonResponseSingle = result as? NSDictionary
        print(" JSON Response :- \(String(describing: jsonResponseSingle))"
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您应该能够对 JSON 执行任何您需要执行的操作。我应该注意到currentMonthandcurrentYear现在是类型Int,如果你需要它们作为字符串,你可以通过说String(currentMonth)and来转换String(currentYear)