2012-09-12 44 views
0

我有一個應用程序需要下載聲音文件才能正常工作。當我開始使用NsurlConnection下載時,我的應用程序會掛起

我正在使用NSURLConnection異步下載我的文件,它的大小超過20Mb。 爲了跟蹤下載的百分比,我放置了一個progressBarView,並且我使用Apple建議的代理方法NSUrlConnection

NSURLRequest *theRequest=[NSURLRequest requestWithURL:soundFileURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0]; 
// create the connection with the request 
// and start loading the data 
NSURLConnection *theConnection; 

theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

//[theConnection cancel]; 
//[theConnection start]; 
if (theConnection) { 
    // Create the NSMutableData that will hold 
    // the received data 
    // receivedData is declared as a method instance elsewhere 
    receivedData=[[NSMutableData data] retain]; 
} else { 
    // inform the user that the download could not be made 
} 

和委託方法

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ 
    [receivedData appendData:data]; 
} 

和So ...

當我開始下載,界面掛起不時和progressView掛起也是如此。

一個值得注意的事情,也許是另一個問題: 我禁用了用戶界面,所以用戶必須等到下載完成,當然,我給他一個消息告訴他。 Apple會否拒絕我的應用程序?我非常擔心的是

感謝您閱讀我的問題:)默認的NSURLConnectionDelegate

+0

附加活動的指標在動畫啓動和停止時animationg完成下載 –

回答

1

NSUrlConnection事件發送到主線程。您應該爲此連接創建新的池和runloop,並確保它在後臺處理。這裏是在後臺下載圖片的例子。它使用修改的NSOperationQueue和NSOperation,但你可以很容易地修改它下載你的文件。 LinkedImageFetcher on developer.apple.com

+0

謝謝你,我想通了,是什麼問題! 在didreceivedata委託方法 我正在寫數據到一個文件,使其變慢!是的,這是愚蠢的! 我只是移動[ercdata writeToFile:fileDir自動:YES]; 到didfinish委託方法。 –

0
//1 First allocate NSOperationQueue object and set number of concurrent operations to execute at a time 

NSOperationQueue *thumbnailQueue = [[NSOperationQueue alloc] init]; 
    thumbnailQueue.maxConcurrentOperationCount = 3; 
// load photo images in the background 
    __weak BHCollectionViewController *weakSelf = self; 
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ 
     UIImage *image = [photo image]; 

     dispatch_async(dispatch_get_main_queue(), ^{ 
      // then set them via the main queue if the cell is still visible. 

       cell.imageView.image = image; 
      } 
     }); 
    }]; 

    operation.queuePriority = (indexPath.item == 0) ? 
     NSOperationQueuePriorityHigh : NSOperationQueuePriorityNormal; 

    [thumbnailQueue addOperation:operation]; 

創建照片級的NSObject,並添加以下方法

- (UIImage *)image 
{ 
    if (!_image && self.imageURL) { 
     NSData *imageData = [NSData dataWithContentsOfURL:self.imageURL]; 
     UIImage *image = [UIImage imageWithData:imageData scale:[UIScreen mainScreen].scale]; 

     _image = image; 
    } 

    return _image; 
} 
+0

這個答案如何與問題相關? – HAS

相關問題