iosjsonswift3

Get Current month and year and Passing to API iOS Swift?


I have a func in which I have to pass current month and year parameters to Fetch API in Swift 3. If I pass hardcoded in parameters I am getting the same response but I am not able to do it with current month and year. Code:-

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))"
}

Solution

  • You have no values for currentMonth and currentYear, so you must make some.

    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))"
        }
    }
    

    Now you should be able to do whatever you need to do with the JSON. I should note that currentMonth and currentYear are now of type Int, if you need them as Strings you can just convert by saying String(currentMonth) and String(currentYear).