我可以在后台使用 NSTimer 吗?

发布于 2024-11-24 01:09:43 字数 6086 浏览 1 评论 0原文

我使用

NSString *urlStr=[NSString stringWithFormat: @"http://xxx.xxx.xxx.xxx:8080/fft/getautodisplaydelay"];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;  
NSError *error = [[NSError alloc] init];  
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];  
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Delay is %@",result);

timer = [NSTimer scheduledTimerWithTimeInterval:(5)
                                         target:self 
                                       selector:@selector(loginunlogin:) 
                                       userInfo:nil 
                                        repeats:YES];
UILocalNotification *localNotif =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];



}

-(void) loginunlogin:(NSTimer *)theTimer{

NSString *urlStr=[NSString stringWithFormat: @"http://xxx.xxx.xxx.xxx:8080/fft/getautodisplaydelay"];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;  
NSError *error = [[NSError alloc] init];  
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];  
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Delay is %@",result);
delay=[result floatValue];
if([result isEqual:@"false"]==TRUE){

    NSLog(@"Delay %@",result);
}else{

    NSLog(@"User logged delay is %@",result);       
    [timer invalidate];
    timer=nil;
    delay=[result floatValue];
    NSTimer *timer1 = [NSTimer scheduledTimerWithTimeInterval: delay target:self selector:@selector(targetMethod:)
                                                userInfo:nil repeats:YES];
}
}

-(void) targetMethod: (NSTimer*)theTimer {
mapView =[[MKMapView alloc] init];
mapView.showsUserLocation=YES;
float mylo =mapView.userLocation.coordinate.longitude;
float myla =mapView.userLocation.coordinate.latitude;
NSString *str1 =[[NSString alloc] initWithFormat:@"%f",mylo];
NSString *str2 =[[NSString alloc] initWithFormat:@"%f",myla];
NSLog(@"longi %@",str1);
NSLog(@"latit %@",str2);


NSString *req=[NSString stringWithFormat: @"http://xxx.xxx.xxx.xxx:8080/fft/messages/getnewmessagescount?longitude=%@&latitude=%@",str1,str2];
NSURL *url = [NSURL URLWithString:req];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;  
NSError *error = [[NSError alloc] init];  
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];  
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

NSLog(@"%@",request);
if ([result isEqual: @"0"])
{
    NSLog(@"No messages");
        }else{
    if ([result isEqual:@"false"]) {
    NSLog(@"Not logged");

    }else{
        NSString *path = [NSString stringWithFormat:@"%@%@", 
                          [[NSBundle mainBundle] resourcePath],
                          @"/tada.wav"];

        //declare a system sound id
        SystemSoundID soundID;

        //Get a URL for the sound file
        NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];

        //Use audio sevices to create the sound
        AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);

        //Use audio services to play the sound
        AudioServicesPlaySystemSound(soundID);

        NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

        // Get the current date
        NSDate *Date = [NSData date];

        // Break the date up into components
        NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) 
                                                       fromDate:Date];
        NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) 
                                                       fromDate:Date];

        // Set up the fire time
        NSDateComponents *dateComps = [[NSDateComponents alloc] init];
        [dateComps setDay:[dateComponents day]];
        [dateComps setMonth:[dateComponents month]];
        [dateComps setYear:[dateComponents year]];
        [dateComps setHour:[timeComponents hour]];
        // Notification will fire in one minute
        [dateComps setMinute:[timeComponents minute]];
        [dateComps setSecond:[timeComponents second]];
        NSDate *itemDate = [calendar dateFromComponents:dateComps];
        [dateComps release];

        UILocalNotification *localNotif = [[UILocalNotification alloc] init];
        if (localNotif == nil)
            return;
        localNotif.fireDate = itemDate;
        localNotif.timeZone = [NSTimeZone defaultTimeZone];

        // Notification details
        localNotif.alertBody = [[NSString alloc] initWithFormat:@"Your have got (%@) new messages",result];
        // Set the action button
        localNotif.alertAction = @"View";

        localNotif.soundName = UILocalNotificationDefaultSoundName;
        localNotif.applicationIconBadgeNumber = 1;

        // Specify custom data for the notification
        NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
        localNotif.userInfo = infoDict;

        // Schedule the notification
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
        [localNotif release];            NSLog(@"bla %@",result);

    }}
}

如何更改它在后台运行的代码

I use

NSString *urlStr=[NSString stringWithFormat: @"http://xxx.xxx.xxx.xxx:8080/fft/getautodisplaydelay"];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;  
NSError *error = [[NSError alloc] init];  
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];  
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Delay is %@",result);

timer = [NSTimer scheduledTimerWithTimeInterval:(5)
                                         target:self 
                                       selector:@selector(loginunlogin:) 
                                       userInfo:nil 
                                        repeats:YES];
UILocalNotification *localNotif =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];



}

-(void) loginunlogin:(NSTimer *)theTimer{

NSString *urlStr=[NSString stringWithFormat: @"http://xxx.xxx.xxx.xxx:8080/fft/getautodisplaydelay"];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;  
NSError *error = [[NSError alloc] init];  
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];  
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Delay is %@",result);
delay=[result floatValue];
if([result isEqual:@"false"]==TRUE){

    NSLog(@"Delay %@",result);
}else{

    NSLog(@"User logged delay is %@",result);       
    [timer invalidate];
    timer=nil;
    delay=[result floatValue];
    NSTimer *timer1 = [NSTimer scheduledTimerWithTimeInterval: delay target:self selector:@selector(targetMethod:)
                                                userInfo:nil repeats:YES];
}
}

-(void) targetMethod: (NSTimer*)theTimer {
mapView =[[MKMapView alloc] init];
mapView.showsUserLocation=YES;
float mylo =mapView.userLocation.coordinate.longitude;
float myla =mapView.userLocation.coordinate.latitude;
NSString *str1 =[[NSString alloc] initWithFormat:@"%f",mylo];
NSString *str2 =[[NSString alloc] initWithFormat:@"%f",myla];
NSLog(@"longi %@",str1);
NSLog(@"latit %@",str2);


NSString *req=[NSString stringWithFormat: @"http://xxx.xxx.xxx.xxx:8080/fft/messages/getnewmessagescount?longitude=%@&latitude=%@",str1,str2];
NSURL *url = [NSURL URLWithString:req];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;  
NSError *error = [[NSError alloc] init];  
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];  
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

NSLog(@"%@",request);
if ([result isEqual: @"0"])
{
    NSLog(@"No messages");
        }else{
    if ([result isEqual:@"false"]) {
    NSLog(@"Not logged");

    }else{
        NSString *path = [NSString stringWithFormat:@"%@%@", 
                          [[NSBundle mainBundle] resourcePath],
                          @"/tada.wav"];

        //declare a system sound id
        SystemSoundID soundID;

        //Get a URL for the sound file
        NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];

        //Use audio sevices to create the sound
        AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);

        //Use audio services to play the sound
        AudioServicesPlaySystemSound(soundID);

        NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

        // Get the current date
        NSDate *Date = [NSData date];

        // Break the date up into components
        NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) 
                                                       fromDate:Date];
        NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) 
                                                       fromDate:Date];

        // Set up the fire time
        NSDateComponents *dateComps = [[NSDateComponents alloc] init];
        [dateComps setDay:[dateComponents day]];
        [dateComps setMonth:[dateComponents month]];
        [dateComps setYear:[dateComponents year]];
        [dateComps setHour:[timeComponents hour]];
        // Notification will fire in one minute
        [dateComps setMinute:[timeComponents minute]];
        [dateComps setSecond:[timeComponents second]];
        NSDate *itemDate = [calendar dateFromComponents:dateComps];
        [dateComps release];

        UILocalNotification *localNotif = [[UILocalNotification alloc] init];
        if (localNotif == nil)
            return;
        localNotif.fireDate = itemDate;
        localNotif.timeZone = [NSTimeZone defaultTimeZone];

        // Notification details
        localNotif.alertBody = [[NSString alloc] initWithFormat:@"Your have got (%@) new messages",result];
        // Set the action button
        localNotif.alertAction = @"View";

        localNotif.soundName = UILocalNotificationDefaultSoundName;
        localNotif.applicationIconBadgeNumber = 1;

        // Specify custom data for the notification
        NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
        localNotif.userInfo = infoDict;

        // Schedule the notification
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
        [localNotif release];            NSLog(@"bla %@",result);

    }}
}

How to change code that it works in background

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酷到爆炸 2024-12-01 01:09:43

我使用此代码在我的应用程序进入后台时播放声音,您可以自定义它以供自己使用

- (void)applicationDidEnterBackground:(UIApplication *)application{
    backgroundTask = [application beginBackgroundTaskWithExpirationHandler: ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (backgroundTask != UIBackgroundTaskInvalid)
            {
                [application endBackgroundTask:backgroundTask];
                backgroundTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        [NSThread sleepForTimeInterval:3];
        [self startPlayingInBackground:@"default.aif"];
        NSLog(@"Time remaining: %f",[application backgroundTimeRemaining]);

        dispatch_async(dispatch_get_main_queue(), ^{
            if (backgroundTask != UIBackgroundTaskInvalid)
            {
                // if you don't call endBackgroundTask, the OS will exit your app.
                [application endBackgroundTask:backgroundTask];
                backgroundTask = UIBackgroundTaskInvalid;
            }
        });
    });
}

下面的行是在其中播放声音的代码,这是我的目标c函数

[self startPlayingInBackground:@"default.aif"];

I am using this code to play the sound when my application enter into background you can customize it for your own use

- (void)applicationDidEnterBackground:(UIApplication *)application{
    backgroundTask = [application beginBackgroundTaskWithExpirationHandler: ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (backgroundTask != UIBackgroundTaskInvalid)
            {
                [application endBackgroundTask:backgroundTask];
                backgroundTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        [NSThread sleepForTimeInterval:3];
        [self startPlayingInBackground:@"default.aif"];
        NSLog(@"Time remaining: %f",[application backgroundTimeRemaining]);

        dispatch_async(dispatch_get_main_queue(), ^{
            if (backgroundTask != UIBackgroundTaskInvalid)
            {
                // if you don't call endBackgroundTask, the OS will exit your app.
                [application endBackgroundTask:backgroundTask];
                backgroundTask = UIBackgroundTaskInvalid;
            }
        });
    });
}

The line below is the code with help of which m playing the sound it's my objective c function all

[self startPlayingInBackground:@"default.aif"];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文