Reputation: 261
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))"
}
Upvotes: 0
Views: 2839
Reputation: 3215
let today = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy"
let year = dateFormatter.string(from: today)
dateFormatter.dateFormat = "MM"
let month = dateFormatter.string(from: today)
e.g. year = 2017 month = 10
per @maddy
var calendar = NSCalendar.current
let today = Date()
let desiredComponents = Set<Calendar.Component>([.month, .year])
calendar.timeZone = TimeZone(identifier: "UTC")!
let components = calendar.dateComponents(desiredComponents, from: today)
components.year
components.month
Upvotes: 0
Reputation: 626
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)
.
Upvotes: 6