0

I can't transform a date string and show it in the form of a .text of a Label. In particular I have created a Model in which the variable "createdAt" must be of type Date, however when I download the JSON I receive the date in the form of a String and I try to convert it I get an error.

then when from the viewController I go to assign the .text variables with the data I downloaded from the JSON, obviously I cannot assign the Date to the label

Am I wrong to do the transformation from string to date in my DownloadManager when downloading the JSON? Does the conversion need to be done in my ViewController?

My MODEL

    class AddressBookModel {
    
    var id : NSInteger = 0
    var createdAt : Date = Date()
    var fullname : String = ""
    var avatar : String = ""
    var phone : String = ""
    var company : String = ""
    var email : String = ""
    
}



My DownloadManager

import Alamofire
import UIKit


class DownloadManager {
    
    static let shared = DownloadManager()
    
    var ViewController : ViewController!
    
    var storage : [AddressBookModel] = []
    
    func downloadJSON(_ url : String) {
        
        debugPrint("scarico: " + url)
        AF.request(url, method: .get).responseJSON { response in
                        
            if let er = response.error{
                print("ERRORE: " + er.localizedDescription)
            }
            
            guard let ilJson = response.value else {
                print("JSON Nil")
                return
            }
            
            guard let json = JSON(ilJson).array else { return }
            
            self.storage = []
            
            let totale = json.count
            
            for i in 0..<totale {
               
                let model = AddressBookModel()
                                
                if let addId = json[i]["id"].string {
                    model.id = Int(addId)!
                }

                if let addCreated = json[i]["createdAt"].string {
//                    var time = NSDate()
//                    var formatter = DateFormatter()
//                    formatter.dateFormat = "dd-MM"
//                    var formatteddate = formatter.string(from: time as Date)
//                    model.createdAt = formatteddate
                }
                
                if let addName = json[i]["fullname"].string {
                    model.fullname = addName
                }
                
                if let addImage = json[i]["avatar"].string {
                    model.avatar = addImage
                }
                
                if let addPhone = json[i]["phone"].string {
                    model.phone = addPhone
                }
                
                if let addCompany = json[i]["company"].string {
                    model.company = addCompany
                }
                
                if let addEmail = json[i]["email"].string {
                    model.email = addEmail
                }

                self.storage.append(model)
            }
            
            self.ViewController.reloadTable()            
        }
    }
}


My ViewController where I assign the trext to the variables

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AddressCell

        cell.imageCover.image = UIImage(named: "objcicon")
        
        let name = DownloadManager.shared.storage[indexPath.row]
        
        cell.labelFullName.text = name.fullname
//        cell.labelCreatedAt.text = name.createdAt
        cell.labelPhone.text = name.phone
        cell.labelCompany.text = name.company
        cell.labelEmail.text = name.email
        
        cell.labelId.text = "#\(indexPath.row + 1)"
        
        cell.labelId.layer.cornerRadius = 17
        
        cell.richiesta = AF.request(name.avatar, method: .get).responseData { rispostaServer in
            
            if rispostaServer.response != nil {
                if rispostaServer.request?.url?.absoluteString ==
                    cell.richiesta?.request?.url?.absoluteString {
                    
                    if let icona = rispostaServer.data {
                        cell.imageCover.image = UIImage(data: icona)
                    }
                }
            } else {
                print("errore")
            }
        }
        
        return cell
    }
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • What error do you get when converting, what is the format of the json date string? – Joakim Danielson Nov 17 '20 at 16:54
  • @JoakimDanielson the error where I write the DateFormatter is : Cannot assign value of type "String" to type "Date" –  Nov 17 '20 at 16:57
  • @JoakimDanielson I Receive this from JSON "createdAt":"2020-09-21T18:24:36.787Z", –  Nov 17 '20 at 16:58
  • Hi, you can do when you decode json to your model or in ViewController. Take a look at https://useyourloaf.com/blog/swift-codable-with-custom-dates/, https://stackoverflow.com/questions/36861732/convert-string-to-date-in-swift – Vladyslav Shmatok Nov 17 '20 at 17:07
  • @ВладиславШматок i red thanks, bug I don't understand.. what should I write in my downlaodManager when I download from the “createdAt” JSON? here : if let addCreated = json[i]["createdAt"].string –  Nov 17 '20 at 17:18
  • @user12147631 forget about SwiftyJSON and read about Codable protocol. – Leo Dabus Nov 17 '20 at 19:37

0 Answers0