0

尝试获取 JSON 文件时出现此错误。

致命错误:在展开可选值时意外发现 nil:文件 /Volumes/Data/Models.swift,第 40 行

我的代码中的第 40 行:

static func fetchFeaturedSearch(_ completionHandler: @escaping (FeaturedSearch) -> ()) {

当我复制 JSON 数据并将其放在静态文件位置时,它就像一个魅力。但是当试图从搜索服务中读取 json 数据时,我遇到了错误。

然而数据看起来完全一样!

请帮我解决一下这个。

服务器 json 文件:(导致错误)

https://nabulsiapps.com/articles-flutter/search/?lang=en&search=god&platform=ios

静态 JSON 文件上的相同文件:(有效)

http://alhudagroup-tr.com/ios/json/searchSample.json

这是主要代码:

struct FeaturedSearch: Decodable {
    var TotalNo: SearchCategory? 
    var categories: [SearchCategory]?
}


struct SearchCategory: Decodable {

    let categoryName: String?
    let categoryIcon: String?
    let categoryId: Int?
    let count: Int?
    let articles: [articlesList]?

    static func fetchFeaturedSearch(_ completionHandler: @escaping (FeaturedSearch) -> ()) {
let urlString =  "https://nabulsiapps.com/articles-flutter/search/?lang=en&search=god&platform=ios"

        //print(urlString)
        
        URLSession.shared.dataTask(with: URL(string: urlString)!, completionHandler: { (data, response, error) -> Void in
            guard let data = data else { return }
            if let error = error {
                print(error)
                return
            }
            do {
                let decoder = JSONDecoder()
                let featuredSearch = try decoder.decode(FeaturedSearch.self, from: data)
                //print(featuredSearch)
                DispatchQueue.main.async(execute: { () -> Void in
                    completionHandler(featuredSearch)
                })
                
            } catch let err {
                print(err)
            }
        }) .resume()
    }
}

struct articlesList: Decodable {
    
    let id: Int?
    let old_id: Int?
    let title: String?
    let date: String?
    let imageUrl: String?
    let has_video: Int?
}
4

0 回答 0