2013-04-30 24 views
6

Tôi có một số NSURLConnection trong phân lớp ô xem bảng có thể tải xuống hầu hết các tệp. Tôi nhận thấy, tuy nhiên, một số không bắt đầu tải xuống, và thời gian ra ngoài. Một ví dụ sẽ là URL this, đây chỉ là tệp zip thử nghiệm tải xuống tốt trong bất kỳ trình duyệt nào khác. Heres mã của tôi để tải xuốngiOS NSURLConnection không tải xuống các tệp từ một số URL nhất định

-(void)downloadFileAtURL:(NSURL *)url{ 
    self.downloadedData = [[NSMutableData alloc] init]; 
    self.url = url; 
    conn = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:self.url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1200.0] delegate:self startImmediately:YES]; 
} 

- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response 
{ 
    int statusCode = [response statusCode]; 
    if (statusCode == 200){ 
     self.fileName.text = response.URL.lastPathComponent; 
     self.respo = response; 
     expectedLength = [response expectedContentLength]; 
    } 
} 

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ 
    CFStringRef mimeType = (__bridge CFStringRef)[_respo MIMEType]; 
    CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType, NULL); 
    CFStringRef extension = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension); 
    NSString *fileName = [NSString stringWithFormat:@"%@.%@", [[_respo suggestedFilename] stringByDeletingPathExtension], (__bridge NSString *)extension]; 
    [[NSFileManager defaultManager] createFileAtPath:[[self docsDir] stringByAppendingPathComponent:[NSString stringWithFormat:@"Downloads/%@", fileName]] contents:_downloadedData attributes:nil]; 
} 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ 
    NSLog(@"Download failed with error: %@", error); 
} 

Bất kỳ ai thấy điều gì có thể gây ra điều này?

Heres lỗi:

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x1fd2c650 
{NSErrorFailingURLStringKey=http://download.thinkbroadband.com/10MB.zip, 
NSErrorFailingURLKey=http://download.thinkbroadband.com/10MB.zip, 
NSLocalizedDescription=The request timed out., NSUnderlyingError=0x1fdc90b0 "The request timed out."} 
+0

Triển khai phương thức giao thức 'connection: didFailWithError:' và xem bạn gặp phải lỗi gì. – Malloc

+0

@Malloc xấu của tôi, tôi quên đăng bài đó. Nó chỉ nói rằng kết nối đã hết thời gian chờ. –

+0

Ok, vậy bạn gặp phải lỗi gì? – Malloc

Trả lời

3

"Tôi có một NSURLConnection trong phân lớp ô xem bảng" - không bao giờ làm điều này. Như Sung-Pil Lim đã chỉ ra chính xác, các ô TableView sẽ được tái sử dụng có thể gây ra vấn đề này.

Dù sao, dữ liệu phản hồi của kết nối của bạn là thuộc tính của mô hình. Mô hình có thể gói gọn cách thức dữ liệu này được đưa vào dữ liệu này. Nếu dữ liệu đó không có sẵn ngay lập tức khi nó sẽ được truy cập, nó sẽ cung cấp một giá trị "giữ chỗ" thay thế và bắt đầu một tác vụ không đồng bộ lấy dữ liệu này.

Giả sử thuộc tính của mô hình, một hình ảnh, sẽ được truy cập bởi bộ điều khiển chế độ xem để hiển thị theo chế độ xem. Mô hình vẫn chưa tải hình ảnh thực tế của nó - và do đó nó trả về một "hình ảnh giữ chỗ" để cho phép hiển thị một cái gì đó. Nhưng đồng thời mô hình bắt đầu một tác vụ không đồng bộ để tải hình ảnh. Khi kết nối này được tải xong với dữ liệu, mô hình sẽ cập nhật nội bộ của nó - do đó thay thế trình giữ chỗ bằng hình ảnh thực. Bản cập nhật của thuộc tính phải được thực hiện trên luồng chính - vì các khung nhìn UIKit cũng có thể truy cập cùng một thuộc tính.

Trong khi khởi tạo, Trình điều khiển chế độ xem đã đăng ký với tư cách người quan sát thuộc tính của mô hình (xem KVO). Khi thuộc tính của mô hình được cập nhật, bộ điều khiển sẽ được thông báo. Trình điều khiển Chế độ xem sau đó thực hiện các hành động thích hợp để chế độ xem sẽ được vẽ lại và hiển thị giá trị được cập nhật mới.

Mô hình của bạn phải có phương thức "hủy", sẽ được gửi tới mô hình từ bộ điều khiển khi giá trị thực tế của thuộc tính của mô hình không bắt buộc nữa. Ví dụ: người dùng đã chuyển sang chế độ xem khác (xem viewWillDisappear).

-1

đôi kiểm tra địa chỉ url của bạn phù hợp với RFC 2396. vì vậy nó phải bao gồm HTTP: //

+0

các url mà anh ta đăng làm –

2

tôi đã cố gắng mã của bạn.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ 
    [self.downloadedData appendData:data]; 
    NSLog(@"%d", data.length); 
} 
2013-05-04 01:51:13.811 SomethingTodo[2732:c07] 1124 
2013-05-04 01:51:13.856 SomethingTodo[2732:c07] 1448 
2013-05-04 01:51:14.075 SomethingTodo[2732:c07] 1448 
2013-05-04 01:51:17.180 SomethingTodo[2732:c07] 1448 
2013-05-04 01:51:17.295 SomethingTodo[2732:c07] 1448 

Đó là làm việc ... trên ViewController

'lỗi yêu cầu thời gian chờ' đã được đưa đến kết nối mạng. hoặc ...

Bạn đang định lại UITableViewCell? Nếu bạn khởi tạo cho các mã tái sử dụng tế bào đối phó với kết nối. có thể gây rắc rối. Chỉ là tôi nghĩ.

Nếu bạn đính kèm thêm mã của mình. Tôi có thể giúp bạn nhiều hơn thế này không.

0

Tôi sẽ bắt đầu bằng phương tiện chặn và chỉ sử dụng mã cơ bản để tải xuống. Tải nhiều NSLog (s) để theo dõi mọi thứ. Nếu điều đó hoạt động, hãy tiếp tục thêm mã tùy chỉnh của bạn và xem liệu bạn có gặp lỗi không. Tôi đề xuất mã NSURLConnection cơ bản:

-(void)startDownloading:(NSString *)URLaddress{ 
NSLog(@"start downloading from: %@",URLaddress); 
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:[URLaddress stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]] 
              cachePolicy:NSURLRequestUseProtocolCachePolicy 
             timeoutInterval:60.0]; 
__unused NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ 
NSLog(@"didReceiveResponse: %@", response); 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ 
NSLog(@"didReceiveData"); 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ 
NSLog(@"Connection failed! Error - %@ %@",[error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ 
NSLog(@"connectionDidFinishLoading"); 
} 
0

thử bằng HCDownloadViewController và bạn có thể kiểm tra url nào không được tải xuống. và đồng bộ hóa lần tiếp theo cho url cụ thể chưa được tải xuống.

tập tin .h

#import "HCDownloadViewController.h" 
@interface HomeViewController_iPhone : UIViewController<HCDownloadViewControllerDelegate> 
{ 
    HCDownloadViewController *tblDownloadHairStyle; 

} 
@property (nonatomic,retain) HCDownloadViewController *tblDownloadHairStyle; 

.m tập tin

#define kAppDirectoryPath NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) 

@synthesize tblDownloadHairStyle

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    tblDownloadHairStyle=[[HCDownloadViewController alloc] init]; 
    tblDownloadHairStyle.delegate=self; 
} 
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response 
{ 

    [self createDocumentDirectory:@"Downloaded_HairStyle"]; 
    NSString *pathHair=[self getDocumentDirectoryPath:@"Downloaded_HairStyle"]; 
    tblDownloadHairStyle.downloadDirectory = pathHair; 
    ////You can put url in for loop, it create queue for downloading. 
    [tblDownloadHairStyle downloadURL:[NSURL URLWithString:@"yourUrl"] userInfo:YourResponseDictonary]; 
} 


-(void)createDocumentDirectory:(NSString*)pStrDirectoryName 
{ 
    NSString *dataPath = [self getDocumentDirectoryPath:pStrDirectoryName]; 

    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) 
     [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:NULL]; 
} 

-(NSString*)getDocumentDirectoryPath:(NSString*)pStrPathName 
{ 
    NSString *strPath = @""; 
    if(pStrPathName) 
     strPath = [[kAppDirectoryPath objectAtIndex:0] stringByAppendingPathComponent:pStrPathName]; 

    return strPath; 
} 


#pragma mark- 
#pragma mark-HCDownloadViewController Delegate Method 
- (void)downloadController:(HCDownloadViewController *)vc startedDownloadingURL:(NSURL *)url userInfo:(NSDictionary *)userInfo { 

} 

- (void)downloadController:(HCDownloadViewController *)vc finishedDownloadingURL:(NSURL *)url toFile:(NSString *)fileName userInfo:(NSDictionary *)userInfo { 

    if (vc==tblDownloadHairStyle) { 
     if ([tblDownloadHairStyle numberOfDownloads]==0) { 

      NSLog(@"AllDownLoad are complete"); 
     } 
    } 
} 
- (void)downloadController:(HCDownloadViewController *)vc failedDownloadingURL:(NSURL *)url withError:(NSError *)error userInfo:(NSDictionary *)userInfo { 
    NSLog(@"failedDownloadingURL=%@",url); 
} 

https://github.com/H2CO3/HCDownload

-1

Bạn có bất cứ thư viện (TestFlight, UA, vv) trong dự án? Hãy thử xóa chúng và kiểm tra lại. Chúng tôi đã có một ứng dụng sử dụng NSUrlConnection với TestFlight SDK đã gây ra tất cả các loại sự cố mạng rời rạc.

NSURLConnection timing out

ASIHTTPRequest request times out

https://github.com/AFNetworking/AFNetworking/issues/307

+0

Liên kết đầu tiên 'NSURLConnection time out' dùng để chỉ mã không có khả năng hoạt động chính xác - và do đó không có dấu hiệu tốt về vấn đề thực sự. – CouchDeveloper

0

chấp nhận bất kỳ phản ứng với mã phản hồi http phạm vi 200-299 và vô hiệu hóa bộ nhớ đệm trên http-connector.

Các vấn đề liên quan