【问题标题】:iOS UISwitch keep sending message every 4 secondiOS UISwitch 保持每 4 秒发送一次消息
【发布时间】:2023-08-12 18:07:01
【问题描述】:

我有一个带有 uiswitch 的聊天应用程序。如果开关按钮打开,我希望应用程序每 3 秒连续发送一次“hi”,即使应用程序处于后台模式。我知道我可以使用 NSTimer,但我真的不知道如何在这段代码中实现它(这是我第一次开发 iOS 应用程序)。请帮我解决这个问题。

我的代码是:

// Allocate, initialize, and add the automatic button.
_AutomaticSend = [[UISwitch alloc] initWithFrame:CGRectMake([self width] - 50.0, textAreaY + Center(160.0, textAreaHeight), 50.0, 50.0)];
[_AutomaticSend addTarget:self action:@selector(changeSwitch:) forControlEvents:UIControlEventValueChanged];

// Switch action
//NSUInteger counter = 0;

- (void)changeSwitch:(id)sender{

    if([sender isOn]){
        for (int a=1; a<=300; a++)
        {
            //[self performSelector:@selector(changeSwitch:) withObject:_textField afterDelay:70.0];
            [sender setOn:YES animated:YES];
            [_textField setText:@"hi"];
            NSString * text = [_textField text];

            // Update status.

            [[TSNAppContext singleton] updateStatus:text];

            // Add the status to the bubble.
            [self appendLocalPeerTableViewCellWithMessage:text];

        }


       // NSLog(@"Switch is ON");
    } else{
        NSLog(@"Switch is OFF");
    }

}

现在,在所有 300 个“hi”都准备好显示后,应用程序正在显示所有“hi”。但我希望它一个接一个地连续发送。

【问题讨论】:

  • 每 3 秒调用一次函数,而不是每 3 秒收到消息
  • 有什么方法可以每 3 秒自动调用一次我的函数吗?
  • 使用 NStimer 每 4 秒调用一次您的方法

标签: ios objective-c uiswitch


【解决方案1】:
  1. 在您的视图控制器中定义一个NSTimer 实例和一个计数器:

    @property (nonatomic, strong) NSTimer *timer;
    @property (nonatomic, assign) NSInteger counter;
    
  2. 实现定时器触发时的方法:

    - (void)timerAction:(id)sender {
        [_textField setText:@"hi"];
        NSString * text = [_textField text];
    
        // Update status.
    
        [[TSNAppContext singleton] updateStatus:text];
    
        // Add the status to the bubble.
        [self appendLocalPeerTableViewCellWithMessage:text];
    
        // stop the timer after sending for 300 times
        self.counter += 1;
        if (self.counter >= 300) {
            [self.timer invalidate];
            self.timer = nil;
        }
    }
    
  3. 当开关打开时启动计时器:

    - (void)changeSwitch:(id)sender{
        if ([sender isOn]) {
            self.counter = 0;
            self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
        } else {
            // kill the timer when switch is off
            [self.timer invalidate];
            self.timer = nil;
        }
    }
    

但是,您不能让计时器在您的应用进入后台后无限期地继续工作(有一些例外:VoIP、GPS 应用程序等)。请参考官方文档Background Execution

【讨论】:

    【解决方案2】:
    //Nstimer *timer in .h
    

    在你的 UISwitch 方法中这样写

    - (void)changeSwitch:(id)sender{
    
     if([sender isOn]){
    timer=[NSTimer scheduledTimerWithTimeInterval:2.0
     target:self
     selector:@selector(targetMethod)
     userInfo:nil
     repeats:NO];
     }
    else
    {
        [timer invalidate];
    }
    }
    

    targetMethod 像这样

    -(void)targetMethod
     {
    [sender setOn:YES animated:YES];
    [_textField setText:@"hi"];
    NSString * text = [_textField text];
    
    // Update status.
    
    [[TSNAppContext singleton] updateStatus:text];
    
    // Add the status to the bubble.
    [self appendLocalPeerTableViewCellWithMessage:text];
    

    }

    【讨论】:

      【解决方案3】:

      使用NSTimerDocumentation of NSTimer

      .h 文件中声明NSTimer 的属性:

      @property (retain,nonatomic) NSTimer *myTimer;
      
      - (void)changeSwitch:(id)sender
      {
         if([sender isOn]){
         myTimer = [NSTimer scheduledTimerWithTimeInterval: 4 target: self
                                         selector: @selector(AddMessage:) userInfo: nil repeats: YES];
      
         } else{
          [self.timer invalidate];
         }
      }
      

      每 4 秒后,定时器会调用以下函数:

      -(void) AddMessage:(NSTimer*) timer 
      { 
          //Add Message
      }
      

      【讨论】: