我嘗試使用NSURLConnection從「http:// .......」下載(7kb)文件,但徒勞無益。 我聲明瞭所有委託(連接:)方法,但NSMutable對象包含0個字節。 這是爲什麼?無法在iphone模擬器中使用NSURLConnection下載文件
甚至NSLogs連接:方法沒有打印。
編輯:下面添加
.H
@interface URLConnect : NSObject {
NSMutableString *textView;
NSMutableData *responseData;
}
- (void)loadURL;
- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data;
- (void)connectionDidFinishLoading:(NSURLConnection *)conn;
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error;
@end
.m file
#import "URLConnect.h"
@implementation URLConnect
- (void)loadURL {
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://wordpress.org/extend/plugins/about/readme.txt"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(theConnection){
responseData = [[NSMutableData data]retain];
NSLog(@"Connection starting: %@", theConnection);
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"Recieved response with expected length: %i", [response expectedContentLength]);
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"Recieving data. Incoming Size: %i Total Size: %i", [data length], [responseData length]);
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Succeeded! Received %d bytes of data",[responseData length]);
[connection release];
NSLog(@"Connection finished: %@", connection);
NSString *txt = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease];
NSLog(@"%@",txt);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[responseData release];
[connection release];
[textView setString:@"Unable to fetch data"];
}
@end
你做錯了什麼?代碼在這裏會有所幫助。 :) –
我已經添加上面的代碼 – chetan
從頭文件中刪除以下函數聲明,因爲它們是http連接創建的委託。 (NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response;(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response; (無效)連接:(NSURLConnection *)conn didReceiveData:(NSData *)data; - (void)connectionDidFinishLoading:(NSURLConnection *)conn; - (void)連接:(NSURLConnection *)conn didFailWithError:(NSError *)error; 第二個原因可能是您已經使用單獨的類來生成連接。可能你有沒有分配內存到它的對象或使用diff對象來產生con –