Могу ли я использовать NSTimer в фоновом режиме? - PullRequest
0 голосов
/ 15 июля 2011

Я использую

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

    }}
}

Как изменить код, чтобы он работал в фоновом режиме

1 Ответ

0 голосов
/ 12 сентября 2011

Я использую этот код для воспроизведения звука, когда мое приложение входит в фоновый режим, вы можете настроить его для своего собственного использования

- (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 функцией all

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