Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我的JSON获取方法只获取一次_Json_Swift - Fatal编程技术网

我的JSON获取方法只获取一次

我的JSON获取方法只获取一次,json,swift,Json,Swift,我有一个从JSON文件获取数据的方法。当我第一次运行应用程序时,它工作得很好,但当我更新JSON文件中的数据并回顾我的应用程序时,数据并没有改变。我必须删除应用程序并再次上传。我的代码怎么了 let requestURL: NSURL = NSURL(string: "https://www.example.com/json.txt")! let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestU

我有一个从JSON文件获取数据的方法。当我第一次运行应用程序时,它工作得很好,但当我更新JSON文件中的数据并回顾我的应用程序时,数据并没有改变。我必须删除应用程序并再次上传。我的代码怎么了

let requestURL: NSURL = NSURL(string: "https://www.example.com/json.txt")!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
        let session = URLSession.shared
        let task = session.dataTask(with: urlRequest as URLRequest) {
            (data, response, error) -> Void in

            let httpResponse = response as! HTTPURLResponse
            let statusCode = httpResponse.statusCode

            if (statusCode == 200) {
                print("Everything is fine, file downloaded successfully.")

                do{

                    let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String: AnyObject]
                    if let JSONSchools = json["skoly"] as? [[String: AnyObject]]{

                        for school in JSONSchools {

                            if let name = school["nazev"] as? String {

                                if let city = school["mesto"] as? String {

                                    if let id = school["id"] as? String {
                                        self.schools.append(School.init(name: name, city: city, id: id))
                                    }

                                }

                            }
                        }
                        self.fetchFinished = true
                    }

                } catch {
                    print("Error with Json: \(error)")
                }
            }
        }

        task.resume()
    }

感谢您的帮助

您需要再次启动该方法才能查看更新的数据。你的应用程序不会自动找到JSON文件的更新。如果您使用的是视图控制器,您可以尝试将调用此代码从
viewwillappearch()
method在按钮单击或任何其他事件上如何调用此函数?每次用户单击按钮时我都会调用它。单击按钮时不需要刷新self.schools吗?self.schools=[]在打电话之前?这不是问题所在。每次调用该方法之前,我都会这样做。