我可以在后台使用NSTimer吗? [英] Can i use NSTimer in background?

查看:95
本文介绍了我可以在后台使用NSTimer吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用

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

推荐答案

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

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

下面的代码是帮助我播放声音的代码目标c函数全部

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"];

这篇关于我可以在后台使用NSTimer吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆