1

サーバーからデバイスに PDF ファイルをダウンロードしようとしています。これが私が使用しているコードです

- (id)initwithURL:(NSString*)remoteFileLocation andFileName:(NSString*)fileName{

    //Get path to the documents folder
    NSString *resourcePathDoc = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]resourcePath]stringByDeletingLastPathComponent]stringByAppendingString:@"/Documents/"]];
    localFilePath = [resourcePathDoc stringByAppendingString:fileName];

    BOOL fileExists = [[NSFileManager defaultManager]fileExistsAtPath:localFilePath];
    if (fileExists == NO) {
        NSURL *url = [NSURL URLWithString:remoteFileLocation];
        NSData *data = [[NSData alloc] initWithContentsOfURL: url];

        //Write the data to the local file
        [data writeToFile:localFilePath atomically:YES];
    }
    return self;
}

ここで、remoteFileLocation は NSString で、値はhttp://topoly.com/optimus/irsocial/Abs/Documents/2009-annual-report.pdf です。アプリを実行すると、NSData で SIGABRT エラーが発生してクラッシュします。それが提供する唯一の有用な情報は

キャッチされていない例外 'NSInvalidArgumentException' が原因でアプリを終了しています。理由: '-[NSURL の長さ]: 認識されないセレクターがインスタンス 0xc87b600 に送信されました'

これはどのように修正できますか?

4

3 に答える 3

3

PDFファイルのサイズが大きすぎるため、同期ダウンロードを行うとダウンロードに時間がかかりすぎるため、非同期ダウンローダーを作成して使用することをお勧めします。私は同じコードを入れました。

ステップ 1 : ファイル 'FileDownloader.h' を作成します。

#define FUNCTION_NAME   NSLog(@"%s",__FUNCTION__)

#import <Foundation/Foundation.h>

@protocol fileDownloaderDelegate <NSObject>

@optional
- (void)downloadProgres:(NSNumber*)percent forObject:(id)object;

@required

- (void)downloadingStarted;
- (void)downloadingFinishedFor:(NSURL *)url andData:(NSData *)data;
- (void)downloadingFailed:(NSURL *)url;

@end

@interface FileDownloader : NSObject
{

@private
    NSMutableURLRequest *_request;
    NSMutableData *downloadedData;
    NSURL *fileUrl;

    id <fileDownloaderDelegate> delegate;

    double totalFileSize;
}

@property (nonatomic, strong) NSMutableURLRequest *_request;
@property (nonatomic, strong) NSMutableData *downloadedData;
@property (nonatomic, strong) NSURL *fileUrl;

@property (nonatomic, strong) id <fileDownloaderDelegate> delegate;

- (void)downloadFromURL:(NSString *)urlString;

@end

ステップ 2 : FileDownloader.m で .m ファイルを作成する

#import "FileDownloader.h"

@implementation FileDownloader

@synthesize _request, downloadedData, fileUrl;
@synthesize delegate;

- (void)downloadFromURL:(NSString *)urlString
{
    [self setFileUrl:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];

    self._request = [NSMutableURLRequest requestWithURL:self.fileUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0f];
    NSURLConnection *cn = [NSURLConnection connectionWithRequest:self._request delegate:self];
    [cn start];
}


#pragma mark - NSURLConnection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if([delegate respondsToSelector:@selector(downloadingStarted)])
    {
        [delegate performSelector:@selector(downloadingStarted)];
    }

    totalFileSize = [response expectedContentLength];    
    downloadedData = [NSMutableData dataWithCapacity:0];
}

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

    if([delegate respondsToSelector:@selector(downloadProgres:forObject:)])
    {
        [delegate performSelector:@selector(downloadProgres:forObject:) withObject:[NSNumber numberWithFloat:([downloadedData length]/totalFileSize)] withObject:self];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if([delegate respondsToSelector:@selector(downloadingFailed:)])
    {
        [delegate performSelector:@selector(downloadingFailed:) withObject:self.fileUrl];
    }    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if([delegate respondsToSelector:@selector(downloadingFinishedFor:andData:)])
    {
        [delegate performSelector:@selector(downloadingFinishedFor:andData:) withObject:self.fileUrl withObject:self.downloadedData];
    }
}

@end

ステップ3:ファイル#import "FileDownloader.h"をインポートfileDownloaderDelegateしてviewControllerに

ステップ 4: viewCONtroller の .m ファイルで次の Delegate メソッドを定義します。

- (void)downloadingStarted;
- (void)downloadingFinishedFor:(NSURL *)url andData:(NSData *)data;
- (void)downloadingFailed:(NSURL *)url;

ステップ 5 : FileDownloader のオブジェクトを作成し、URL を Download に設定します。

FileDownloader *objDownloader = [[FileDownloader alloc] init];
[objDownloader setDelegate:self];
[objDownloader downloadFromURL:@"Your PDF Path URL here];

ステップ 6 : メソッド内の必要な場所にファイルを保存します - (void)downloadingFinishedFor:(NSURL *)url andData:(NSData *)data;

于 2013-04-17T04:33:20.907 に答える
1

remoteFileLocationパラメータ値は実際にはオブジェクトNSURLであり、NSString. 取得/作成方法を再remoteFileLocation確認し、それが実際に であることを確認してくださいNSString

このコードには他にもいくつかの問題があります。Documents ディレクトリへのパスを作成する適切な方法は次のとおりです。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *localFilePath = [resourcePathDoc stringByAppendingPathComponent:fileName];

BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:localFilePath];
if (!fileExists) {
    NSURL *url = [NSURL URLWithString:remoteFileLocation];
    NSData *data = [[NSData alloc] initWithContentsOfURL:url];

    //Write the data to the local file
    [data writeToFile:localFilePath atomically:YES];
}
于 2013-04-17T00:04:02.017 に答える