2014-01-07 2 views
3

내가 이것을 본 적이 있는지 또는 내 코드에서 다음 동작을 보는 이유에 대한 아이디어가 있을지 궁금해하고 있습니다. 배경 구성이있는 NSURLsession이 있습니다. 프로그램이 포 그라운드에서 실행될 때 주기적으로 다운로드 작업을 시작하고 모든 것이 작동합니다. backgroundcode (xcode)를 시뮬레이션 할 때, 내 작업은 null 값을 얻습니다 (요청 및 세션이 null이 아니더라도). 물론이 경우 내 세션 대리인은 결코 완료 처리자를 해고 당하지 않습니다. 후속 배경 가져 오기를 시뮬레이션하면 나중에 모두 작동합니다. 이 시점에서 시뮬레이터에서 앱을 포 그라운드로 가져 와서 또 다른 배경 가져 오기를 시뮬레이트하면 증상이 완전히 뒤죽박죽이됩니다. 내 appdelegate 클래스에서이 코드를 사용하고 있습니다.다운로드 작업이 null 일 때 Backgroundfetch IOS

귀하의 도움에 크게 감사드립니다.

- (NSURLSession *)FlickrSession 
{ 

if(!_FlickrSession) 
{ 
    NSLog(@"setting new FlickrSession"); 
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:FLICKR_SESSION]; 
    configuration.allowsCellularAccess = NO; 

    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
     _FlickrSession = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; 
     _FlickrSession.sessionDescription = FLICKR_SESSION; 
     NSLog(@" new self is %@", _FlickrSession); 
     NSLog(@"queue in session %@", dispatch_get_current_queue()); 

    }); 
} 
return _FlickrSession; 

} 

-(void) startFlickrFetch 
{ 
// initialize session config and the background session 

[self.FlickrSession getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) 
{ 
    if(![downloadTasks count]) 
    { 
     NSLog(@"new downloadtask session %@", self.FlickrSession.sessionDescription); 


     NSURLRequest *request = [NSURLRequest requestWithURL:[FlickrFetcher URLforRecentGeoreferencedPhotos]]; 
     // NSURLSessionDownloadTask *task = [self.FlickrSession downloadTaskWithURL:[FlickrFetcher URLforRecentGeoreferencedPhotos]]; 
     NSURLSessionDownloadTask *task = [self.FlickrSession downloadTaskWithRequest:request]; 
     task.taskDescription = FLICKR_DOWNLOAD_TASK; 
     NSLog(@"new request %@", request); 
     NSLog(@"new downloadtask %@", task); 
     [task resume]; 
     //task?[task resume]:[self fireBackgroungFetchCompletionHandler];; 
      //[self fireBackgroungFetchCompletionHandler]; 
     NSLog(@"queue in task %@", dispatch_get_current_queue()); 
    } 
    else 
    { 
     NSLog(@"resuming old downloadtask %d", [downloadTasks count]); 
     for(NSURLSessionDownloadTask *task in dataTasks) [task resume]; 

    } 

}]; 
NSLog(@"queue outside the block %@", dispatch_get_current_queue()); 

} 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions 
{ 
    // Override point for customization after application launch. 
    // open the file, if there is no managedContext. this is the case wjere the application was launched directly by user 
    // it did not come from the bckground state; 


    //need to enable background fetch 
    [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum]; 


//[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(documentChangedState) name:UIDocumentStateChangedNotification object: self.document]; 
    NSLog(@"in application didfinishlaunching"); 

    [self openDatabaseFile]; 
    [self startFlickrFetch]; 



    return YES; 
} 

-(void) application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler 
{ 

    self.backgroundFetchCompletionHandler = completionHandler; 
    if(self.document.documentState == UIDocumentStateNormal) 
    { 
     //[self openDatabaseFile]; 

     NSLog(@"in performFetchWithCompletionHandler"); 

     [self startFlickrFetch]; 
    } 

} 

- (void) application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler 
{ 


    self.completionhandler = completionHandler; 
    NSLog(@"handle event for backgroundURLsession***********");  
} 
+0

나는 비슷한 행동을 감지했습니다. 특히, 작업 생성 전에 중단하고 단계적으로 수행하면 아무런 결과도 얻지 못합니다. 작업 생성 후 중단되면 작업이 반환됩니다. 이것은 시뮬레이터에 있습니다. – Felix

+0

동일한 증상 (동일한 장치에서 테스트 됨), 동일한 증상이 나타납니다. ''application : performFetchWithCompletionHandler :''에서''downloadTaskWithRequest :''를 실행할 때, 당신은 nil을 얻는다. – desudesudesu

+0

나는 또한 이것이 실제 장치에서 일어나는 것을 보았습니다. (iOS 7.0.3.) – TJez

답변

0

이것은 배경 가져 오기와 백그라운드 세션의 이상한 상호 작용과 관련이있을 수 있습니다.이 경우에는 조언이 없습니다.

그러나 백그라운드에서 iOS는 비동기 호출을 기다리지 않습니다. getTasksWithCompletionHandler. UIBackgroundTaskIdentifier † 기반 [UIApplication] 시작/종료 작업 (이 경우 "get (세션) 작업 완료 핸들러"블록 내에서 "종료 (app) 작업")로 해당 호출을 래핑하면 해결할 수 있습니다.

그러나 당신이 필요로하는 모든이 카운트 경우, 여기 내가 생각하는 무슨 짓을했는지 간단합니다 : 당신이 작업을 만들 때

NSMutableSet *activeTaskIDs; 

는, 세트에 추가 :

는 바르 만들기 :

[activeTaskIDs addObject:@(task.taskIdentifier)]; 

작업이 완료되면 제거하십시오.

숫자는 비동기가 아닙니다.

† 헷갈려서 종류의 작업이 있습니다. 나는 "앱 작업"대 "세션 작업"이라는 용어로 구별됩니다.