2011-07-15 70 views
0

我用我可以在後臺使用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); 

    }} 
} 

如何改變,它在後臺運行,

+0

你能至少描述你的代碼的作用嗎? – Vladimir

+0

第一部分/ getautodisplaydelay /獲得的NSTimer延遲多久將發生新郵件的請求getnewmessagescount至極回報號碼,如果它不爲null必須證明NSLocalnotification – Ruslan

+0

弗拉基米爾俄羅斯Короченеобоходимочтобывсвёрнутомрежимеработалзапросгетньюмесседжзкаунтивслучаеесли ониестьтосрабатывалNSlocalnotification – Ruslan

回答

0

我使用此代碼來播放聲音時,我的應用程序進入後臺,你可以自定義自己使用

代碼
- (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; 
      } 
     }); 
    }); 
} 

下面的線與幫助下m的播放聲音的代碼,這是我的目標C函數的所有

[self startPlayingInBackground:@"default.aif"]; 
相關問題