Refresh JSON data after a few seconds in swift

回眸只為那壹抹淺笑 提交于 2021-01-28 06:30:46

问题


I want this to update every 4 seconds with fresh data form the url, but i dont know how to do this. This is what i have so far and it works fine but without the refresher! The Refresher needs to work like a youtube subscriber counter that update every 4 seconds or so. I have looked at a timer but i couldn't make it work because (i think) its a searchBarSearchButtonClicked function and the urlRequestid has to have a input! Please help! Thanks!

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()
 }   
}

回答1:


One quick but admittedly clumsy fix would be to store the latest UISearchBar instance from the searchBarSearchButtonClicked parameter in a local instance variable:

var currentSearch: UISearchBar = UISearchBar()
var timer: Timer?

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { 

    currentSearch = searchBar
    // Add the rest of the method code below...
    ... 

}

// Call this method to begin repetition
func repeatSearch() {

    self.timer = Timer.scheduledTimer(withTimeInterval: 4.0, repeats: true, 
    block: { (timer) in
        self.searchBarSearchButtonClicked(self.currentSearch)
    })
}



回答2:


You can achieve it by using the Timer, schedule it for every 4 seconds.

DEMO

FOR iOS 10.0 and Above

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")
    })
}

For below 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")
}

Just replace your code according to the demo. And add this code to your viewController :

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


来源:https://stackoverflow.com/questions/44701410/refresh-json-data-after-a-few-seconds-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!