swift - Trying to DateFormatting Optional String -
currently i'm getting invoice data rails api.
func get(path: string) { let url = nsurl(string: path) let session = nsurlsession.sharedsession() let task = session.datataskwithurl(url!, completionhandler: {data, response, error -> void in if(error != nil) { print(error!.localizeddescription) } { let results = try nsjsonserialization.jsonobjectwithdata(data!, options: nsjsonreadingoptions.mutableleaves) self.delegate.didreceiveapiresults(results as! nsarray) } catch { print("error") } }) task!.resume() }
then pass array results delegate in invoicescontroller:
func didreceiveapiresults(results: nsarray) { let dateformatter = nsdateformatter() dateformatter.dateformat = "yyyy-mm-dd't'hh:mm:ss.sssz" dispatch_async(dispatch_get_main_queue(), { invoice in results { // create individual item invoice.createinmanagedobjectcontext(self.managedobjectcontext, invoicestatus: string(invoice["status"]), invoiceprice: nsdecimalnumber(string: string(invoice["price"])), invoicedate: dateformatter.datefromstring("2015-06-22t17:57:21.313z")!, invoiceduedate: string(invoice["invoice_date"]) ) } }) }
but can't convert invoice["invoice_date"] optional valid date, returns nil.
i've tried things in playground , there works optional value:
let dateformatter = nsdateformatter() dateformatter.dateformat = "yyyy-mm-dd't'hh:mm:ss.sssz" var datestring:string? = "2015-06-22t17:57:21.313z" dateformatter.datefromstring(datestring!)
by using:
invoicedate: dateformatter.datefromstring(string(invoice["invoice_date"]))!
i'm getting error:
fatal error: unexpectedly found nil while unwrapping optional value (lldb)
someone suggestions? i'm using swift 2 on ios 9 platform.
question answered in comments, thought i'd put here:
there problem in cast, , using
invoice["invoice_date"] as! string
solved it.
Comments
Post a Comment