Can i use NSTimer in background?

2019-09-12 02:00发布

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

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-12 02:25

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"];
查看更多
登录 后发表回答