定时器 swift

var timer: Timer?      //刷新时器
 //关闭定时运行
    func stopTimer() {
        self.timer?.invalidate()
        self.timer = nil
    }
    
    //启动定时运行
    func startTimer() {
        if timer == nil {
            self.timer = Timer.scheduledTimer(
                timeInterval: 2,
                target: self,
                selector: #selector(self.getChats),
                userInfo: nil,
                repeats: true)
        }
        
    }




//获取聊天记录
    func getChats(){
        RemoteService.sharedInstance.getChats(lastreceived: self.lastreceived)
        {
            (message,chats) in
            
            if message.code == ApiResultCode.Success.rawValue{
                
                for (_,chat) in chats.enumerated(){
                    self.addChats(chatInfo: chat)
                }
                
                self.tableView.reloadData()
            }else{
                SVProgressHUD.showError(withStatus: message.message)
            }
            
        }
    }

你可能感兴趣的:(定时器 swift)