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 文件中定义以下委托方法

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

第 5 步:创建 FileDownloader 的对象并将 URL 设置为下载它。

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 回答
0

GCD 可用于处理大量文件。如果您愿意,您可以在第二个线程上同步下载文件并回发到主线程。您还可以使用操作队列。

您确实也可以使用 NSURLConnection 中的委托方法,允许您处理主线程上的回调。然而,定义自己的委托已经过时了,因为您可以只从 NSURLConnection 本身实现委托。

于 2014-02-17T08:17:14.850 回答