невозможно загрузить файл с помощью NSURLConnection в симуляторе iphone - PullRequest
0 голосов
/ 24 ноября 2011

Я попытался загрузить файл (7kb) с http: // ......., используя NSURLConnection, но безуспешно. Я объявил все методы делегата (connection :), но объекты NSMutable содержат 0 байтов. Почему это?

И даже NSLogs в связи: методы не были напечатаны.

Редактировать: добавить код ниже

@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

Ответы [ 2 ]

1 голос
/ 24 ноября 2011

Это код для загрузки файла и сохранения его на устройстве или в симуляторе (т.е. на компьютере) ...

Это не точный код, но я надеюсь, что он поможет вам ...

@interface URLConnect : NSObject {

NSMutableString *textView;
NSMutableData *receivedData;
NSURLRequest* DownloadRequest;
NSURLConnection* DownloadConnection;

long long bytesReceived;
long long expectedBytes;

}
@property (nonatomic,retain) NSMutableData *receivedData;
@property (nonatomic, readonly, retain) NSURLRequest* DownloadRequest;
@property (nonatomic, readonly, retain) NSURLConnection* DownloadConnection;


.m file

#import "URLConnect.h"

@implementation URLConnect

// synthesize the properties 

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

    unsigned char byteBuffer[[receivedData length]];
    [receivedData getBytes:byteBuffer];
    NSLog(@"Data === %ld",receivedData);

    NSInteger receivedLen = [data length];
    bytesReceived = (bytesReceived + receivedLen);
    NSLog(@"received Bytes ==  %f",bytesReceived);

    if(expectedBytes != NSURLResponseUnknownLength) 
    {
        NSLog(@"Expected Bytes in if ==  %f",expectedBytes);
        NSLog(@"received Bytes in if ==  %f",bytesReceived);

        float value = ((float) (bytesReceived *100/expectedBytes))/100;
        NSLog(@"Value ==  %f",value);
    }

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [connection release];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    expectedBytes = [response expectedContentLength];
    NSLog(@"%f",expectedBytes);

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // code for downloading file to device or simulator

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"AnyName.txt"];

    unsigned char byteBuffer[[receivedData length]];
    [receivedData getBytes:byteBuffer];

    [self.receivedData  writeToFile:pdfPath atomically:YES];

    [DownloadConnection release];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSURL *targetURL = [NSURL URLWithString:urlString];
    DownloadRequest = [NSURLRequest requestWithURL:targetURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:50.0];
    DownloadConnection = [[NSURLConnection alloc] initWithRequest:DownloadRequest delegate:self];

    if (DownloadConnection) {
        receivedData = [[NSMutableData data]retain];
    }

    // display your textfile here


}
0 голосов
/ 24 ноября 2011

Похоже, вы на самом деле не устанавливали свойство делегата для вашего экземпляра NSURLConnection. Это объясняет, почему NSLog в методах делегатов не выводятся на печать.

...