在Swift 3中取消包装可选时,遇到了零值



我正在迅速编程,并试图在iOS应用程序中显示JSON对象,但是在运行代码时,请继续收到错误"在解开可选值的同时,在未包装的同时发现了错误"。

这是显示JSON的代码:

import Foundation
import UIKit
class EventList
{
    static var listOfEvents = [Event]()
    static var eventService:EventService?
    static func getEventsFromWebService()->[Event]
        // _ siteURL:String, _ searchTerm:String    
    {
        let searchURL = "http://api.eventful.com/json/events/search?
        date=2018&app_key=wjwMpjZWRD7JXHPQ"
        print ("Web Service call = (searchURL)")
        eventService = EventService(searchURL)
        let operationQ = OperationQueue()
        operationQ.maxConcurrentOperationCount = 1
        operationQ.addOperation(eventService!)
        operationQ.waitUntilAllOperationsAreFinished()

        listOfEvents.removeAll()
        let returnedJSON = eventService!.jsonFromResponse
        let JSONObjects = returnedJSON?["event"] as! [[String:String]]
        for eachJSONObject in JSONObjects
        {
            print("Creating Movie object from JSON: (eachJSONObject)")
            listOfEvents.append(Event(eachJSONObject))
        }
        return listOfEvents
    }
    private static func showCreatedList()
    {
        for evt in listOfEvents
        {
            print(evt.displayEvent())
        }
    }
}
class Event
{
    private (set)var title:String
    private (set)var city_name:String
    private (set)var country_name:String
    private (set)var venue_name:String
    private (set)var venue_address:String
    private (set)var start_time:String
    private (set)var url:String
    private (set)var isSaved:Bool
    init?(_ t:String, _ ci:String, _ co:String, _ vn:String, _ va:String, _ 
s:String, _ u:String)
    {
        if ((t == "") || (va == "") || (s == ""))
        {
            return nil
        }
        else
        {
            title = t
            city_name = ci
            country_name = co
            venue_name = vn
            venue_address = va
            start_time = s
            url = u
            isSaved = false
        }
    }
    convenience init(_ JSONObject:[String:String])
    {
        let title = JSONObject["title"]
        let city = JSONObject["city_name"]
        let country = JSONObject["country_name"]
        let venue = JSONObject["venue_name"]
        let address = JSONObject["venue_address"]
        let time = JSONObject["start_time"]
        let url = JSONObject["url"]
        self.init(title!,city!,country!,venue!,address!,time!,url!)!
    }
    func displayEvent()->String
    {
        let strEvent = "(title) will take place at (venue_name)"
        return strEvent
    }
}
class EventService:Operation
{
    var urlReceived: URL?
    var jsonFromResponse: [String:Any]?
    init(_ incomingURLString:String)
    {
        urlReceived = URL(string: 
incomingURLString.addingPercentEncoding(withAllowedCharacters: 
CharacterSet.urlQueryAllowed)!)
    }
    override func main()
    {
        var responseData:Data?
        do
        {
            responseData = try Data(contentsOf: urlReceived!)
            print("Service call (request) successful! Returned: 
(responseData)")
        }
        catch
        {
             print("Service call (request) failed")
        }
        do
        {
            jsonFromResponse = try JSONSerialization.jsonObject(with: 
responseData!,options: .allowFragments) as? [String:Any]
            print("JSON Parser successful. Returned: (jsonFromResponse!)")
        }
        catch
        {
            print("JSON Parser failed")
        }
    }
}

这是我正在使用的JSON的一部分:

{
"last_item": null,
"total_items": "3983377",
"first_item": null,
"page_number": "1",
"page_size": "10",
"page_items": null,
"search_time": "0.129",
"page_count": "398338",
"events": {
  "event": [
    {
      "watching_count": null,
      "olson_path": "America/New_York",
      "calendar_count": null,
      "comment_count": null,
      "region_abbr": "VA",
      "postal_code": "23229",
      "going_count": null,
      "all_day": "0",
      "latitude": "37.5949",
      "groups": null,
      "url": "http://richmond.eventful.com/events/lettermen-/E0-001-
102252139-0?utm_source=apis&utm_medium=apim&utm_campaign=apic",
      "id": "E0-001-102252139-0",

JSON继续显示不同的事件对象。该错误在行上标记:

let JSONObjects = returnedJSON?["event"] as! [[String:String]]

我正在与使用类似代码但不同的JSON数据集的人一起工作,因此我不确定是我的JSON数据还是我的代码是问题。

事先感谢您的任何帮助。

从我乍看之下我可以看到的东西,看来您的json上有零值,但是当初始化类事件时,您说所有字段都是强制性的。

self.init(title!,city!,country!,venue!,address!,time!,url!)!

这些都是强制性的字段,从我可以看到您的JSON只有URL字段,从JSON到您的班级的翻译将重现错误

相关内容

  • 没有找到相关文章

最新更新