Writing JSON file programmatically swift

前端 未结 3 1953
青春惊慌失措
青春惊慌失措 2021-01-07 12:04

im making quiz app and I want to download questions from server in JSON file, parse it and make question object that I will present. I did it so now I want to make an app th

3条回答
  •  时光说笑
    2021-01-07 12:32

    You can use JSONSerialization class for this purpose. Please see the code snippet below cooked up in Playground

    import Foundation
    
    // Dictionary containing data as provided in your question.
    var dictonary : [String : Any] = ["question":"If you want to create a custom class which can be displayed on the view, you can subclass UIView.",
                                      "answers":["True", "False"],
                                      "correctIndex":0,
                                      "module":3,
                                      "lesson":0,
                                      "feedback":"Subclassing UIView gives your class the methods and properties of a basic view which can be placed onto the view."
                                     ]
    
    
    if let jsonData = try JSONSerialization.data(withJSONObject: dictonary, options: .init(rawValue: 0)) as? Data
    {
        // Check if everything went well
        print(NSString(data: jsonData, encoding: 1)!)
    
        // Do something cool with the new JSON data
    }
    

    If you run this code in Xcode playground, you can see your data printed in JSON format Once you have the JSON , you can use the networking library of your choice to send the data over to the server.

提交回复
热议问题