2014-10-06 3 views
2

이 코드를 사용하는 동안 내 자신의 서버에서 동시에 여러 파일을 에디터를 이용해하려고 : 나는 3 개 장의 사진을캐치되지 않는 예외 'NSFileHandleOperationException'

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    // create 
    [[NSFileManager defaultManager] createFileAtPath:strFilePath contents:nil attributes:nil]; 
    _file = [NSFileHandle fileHandleForUpdatingAtPath:strFilePath];// read more about file handle 
    if (_file) { 
     [_file seekToEndOfFile]; 
    } 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)receivedata 
{ 
    //write each data received 
    if(receivedata != nil){ 
     if (_file) { 
      [_file seekToEndOfFile]; 
     } 
     [_file writeData:receivedata]; 
    } 
} 

- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection { 
    //close file after finish getting data; 
    [_file closeFile]; 
} 

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    //do something when downloading failed 
} 
- (IBAction)downloadFromServer:(id)sender { 

     NSLog(@"File now being downloaded"); 
    while (i<=3) { 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    NSURL *strFileURL =[NSURL URLWithString:[NSString stringWithFormat:@"SomePath/pic%d.png", i]]; 

    [request setURL:strFileURL]; 
    NSURLConnection *conection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO]; 
    [conection start]; 
    strFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic%d.png", i]]; 

    } 

} 

, pic1.png, pic2.png 및 pic3.png. 이제이 코드를 실행하면 app은 pic3.png라는 손상된 파일 하나만 저장하고 자동으로 충돌합니다. 세 가지 파일을 모두 다운로드해야하는데, 어디서 잘못 될지 알려주시겠습니까?

답변

0

그래서 실제로, 하나 개의 zip 파일에있는 모든 사진을 넣어 그것을 다운로드하고이 코드를 사용하여 실제 장치에 압축을 해제 한 할 수있는 가장 좋은 방법은 :

dispatch_queue_t queue = dispatch_get_global_queue(
                 DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
    dispatch_async(queue, ^{ 
     NSURL *url = [NSURL URLWithString:@"someDirectory/newPics.zip"]; 
     NSError *error = nil; 
     // 2 
     NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error]; 

     if(!error) 
     { 
      // 3 
      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
      NSString *path = [paths objectAtIndex:0]; 
      NSString *zipPath = [path stringByAppendingPathComponent:@"newPics.zip"]; 

      [data writeToFile:zipPath options:0 error:&error]; 

      if(!error) 
      { 

       ZipArchive *za = [[ZipArchive alloc] init]; 
       // 1 
       if ([za UnzipOpenFile: zipPath]) { 
        // 2 
        BOOL ret = [za UnzipFileTo: path overWrite: YES]; 
        if (NO == ret){} [za UnzipCloseFile]; 

        // 3 
        NSString *imageFilePath = [path stringByAppendingPathComponent:@"newPics/pic1.png"]; 
        //[self removeImage:zipPath]; 


        [[NSFileManager defaultManager] removeItemAtPath:zipPath error: &error]; 

        dispatch_async(dispatch_get_main_queue(), ^{ 

          NSURL *fileURL = [NSURL fileURLWithPath:imageFilePath]; 
          [_webV loadRequest:[NSURLRequest requestWithURL:fileURL]]; 



        }); 

       } 

      } 
      else 
      { 
       NSLog(@"Error saving file %@",error); 
      } 
     } 
     else 
     { 
      NSLog(@"Error downloading zip file: %@", error); 
     } 

    }); 

그것은 빠르고 신뢰할 수있는, 그것을 할 수있는 가장 좋은 방법입니다.

0

이것이 제대로 작동하지 않는다는 것은 명백합니다. 세 가지 비동기 작업을 시작합니다. 비동기 작업을 시작한 후에는 알 수없는 위치에 파일 이름을 저장하지만 위치는 동일 할 수 있습니다. 따라서 첫 번째 비동기 작업이 끝날 때 어떤 파일 이름이 사용됩니까? 힌트 : 당신이 사용할 것이라고 생각하는 사람이 아닙니다.

+0

답장을 보내 주셔서 감사합니다 ... 이것은 처음으로 이런 종류의 상황을 처리하는 ... 코드 스 니펫으로 나를 도울 수 있습니까? 많은 시간을 내 주셔서 감사합니다. –

+0

그것은 소프트웨어입니다. 코드를 작성하십시오. – gnasher729

+0

나는 내 소프트웨어를 써달라고 부탁하는 것이 아니다. 나는 그 상황에서 처음으로 나를 돕기 위해 당신의 요점을 명확히 할 수있는 발췌 문장을 요구하고 있었다. –

0

간단한 while 루프를 사용하여 REQUEST 작업을 반복하지 마십시오. 실제로 Apple 자체에는 라이브러리가 너무 많습니다. 그래서 여기에서 가장 좋은 질문은 "NSOPERATION QUEUE"입니다. 그래서, 더 나은 당신이 애플 개발자 사이트 참고로 확인하실 수 있습니다, 당신은 명확한 아이디어를 얻을 : [1] NSOperation 사용하여 다른 요청 처리 할 수있는 방법에 대한 https://developer.apple.com/library/IOs/documentation/Cocoa/Reference/NSOperationQueue_class/index.html

-처럼 AddOperation, 또는 RemoveOperation, WaitUntilItFinishTheThread을 ..

관련 문제