在swift中几秒后刷新JSON数据

时间:2017-06-22 13:52:20

标签: json swift xcode swift3

我希望每隔4秒更新一次,新的数据来自网址,但我不知道该怎么做。这是我到目前为止,它工作正常,但没有复习! Refresher需要像youtube订阅者计数器一样工作,每4秒左右更新一次。我看了一个计时器,但我无法使它工作,因为(我认为)它是一个searchBarSearchButtonClicked函数,而urlRequestid必须有一个输入!请帮忙!谢谢!

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

    let urlRequestid = URLRequest(url: URL(string: "https://www.mylink.com/\(searchBar.text!.replacingOccurrences(of: " ", with: "%20"))/?__a=1")!)


    if (interstitial.isReady){
        interstitial.present(fromRootViewController: self)
        interstitial = createAndLoadInterstitial()
    }



    let task = URLSession.shared.dataTask(with: urlRequestid) { (data, response, error) in

        if error == nil {
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]

                if let user = json["user"] as? [String : AnyObject] {

                    let profile_pic_url_hd = user["profile_pic_url_hd"] as! String


                    let urlstr = "\(profile_pic_url_hd)"
                    if var comps = URLComponents(string: urlstr) {
                        var path = comps.path
                        var pathComps = path.components(separatedBy: "/")
                        pathComps.remove(at: 2) // this removes the s320x320
                        path = pathComps.joined(separator: "/")
                        comps.path = path
                        if let newStr = comps.string {
                            print(newStr)
                            self.imgURL = "\(newStr)"
                        }
                    }

                    if let bio = user["biography"] as? String {
                        self.bioS = bio



                    }

                    if let naam = user["username"] as? String {
                        self.naamS = naam
                    }

                    if let followed_by = user["followed_by"] as? [String : AnyObject] {
                        self.VolgS = followed_by["count"] as! Int
                    }

                    if let follows = user["follows"] as? [String : AnyObject] {
                        self.volgD = follows["count"] as! Int
                    }
                    if let media = user["media"] as? [String : AnyObject] {
                        self.postS = media["count"] as! Int
                    }


                    }

                if let _ = json["error"] {
                    self.exists = false
                }

                DispatchQueue.main.async {
                    if self.exists{

                        self.imgView.downloadImage(from: self.imgURL!)
                        self.naam.text = "@\(self.naamS ?? "")"
                        if self.bioS == nil {
                             self.bio.text = "This Person has no biography!"
                        }else{
                            self.bio.text = "\(self.bioS ?? "")"

                        }
                        self.volgers.text = "\(self.VolgS!)"
                        self.volgend.text = "\(self.volgD!)"
                        self.post.text = "\(self.postS!)"

                    }else {

                        self.exists = true

                    }
                }


            } catch let jsonError {
                print(jsonError.localizedDescription)


            }
        }
    }

    task.resume()
}

}

2 个答案:

答案 0 :(得分:1)

一个快速但不可否认的笨拙修复方法是将 RewriteCond %{REQUEST_URI} !(jpe?g|png|gif)$ [NC] 参数中的最新UISearchBar实例存储在本地实例变量中:

searchBarSearchButtonClicked

答案 1 :(得分:-1)

您可以使用Timer来实现它,每隔4秒安排一次。

<强>样本

适用于iOS 10.0及以上版本

var timer: Timer?
func callMe() {
    func doSomrThing(str: String) {
        print(str)
    }

    doSomrThing(str: "first time")

    self.timer = Timer.scheduledTimer(withTimeInterval: 4.0, repeats: true, block: { (timer) in
        doSomrThing(str: "after 4 second")
    })
}

适用于iOS 10.0以下

var timer: Timer?
func callMe() {

    self.doSomeThing(str: "first time")

    self.timer = Timer.scheduledTimer(timeInterval: 4.0, target: self, selector: #selector(AddTextVC.timerHandler), userInfo: nil, repeats: true)
}

func doSomeThing(str: String) {
    print(str)
}

func timerHandler() {
    self.doSomeThing(str: "after 4 seconds")
}

只需根据演示替换您的代码即可。 并将此代码添加到viewController:

deinit {
    self.timer?.invalidate()
    self.timer = nil
}