从远程URL下载ios应用程序中的PDF

时间:2014-04-21 06:57:34

标签: ios iphone objective-c ios7 ios7.1

我正在使用下面的代码从URL下载PDF,但我收到了以下输出以及通知和错误。

我的AppDelegate.h

@interface FileDownload2AppDelegate : UIResponder <UIApplicationDelegate , NSURLConnectionDataDelegate>
{
        NSMutableData *receivedData;
}

@property (strong, nonatomic) UIWindow *window;

@end

我的AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        // Override point for customization after application launch.

        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://code.google.com/p/androidnetworktester/downloads/detail?name=1mb.txt"]];
        [NSURLConnection connectionWithRequest:request delegate:self];

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:@"/Users/awsuser8/1.txt"];
        NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://code.google.com/p/androidnetworktester/downloads/detail?name=1mb.txt"]];
        [thedata writeToFile:localFilePath atomically:YES];

        NSLog(@"PDF downloaded");

        return YES;
    }



- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.

    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.

    // receivedData is an instance variable declared elsewhere.
    [receivedData setLength:0];
}


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

    [receivedData appendData:data];
    NSLog(@"receivedData : %@", receivedData);
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    //[connection release];
    // receivedData is declared as a method instance elsewhere
    //[receivedData release];

    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);

    // release the connection, and the data object
   // [connection release];
   // [receivedData release];
}

获取输出:

lockdownd[53] <Notice>: 00281000 __copy_itunes_value_block_invoke: com.apple.mobile.iTunes.store/downloaded-apps -> (null)
lockdownd[53] <Notice>: 01a63000 __copy_itunes_value_block_invoke: com.apple.mobile.iTunes.store/downloaded-apps -> (null)
networkd[79] <Warning>: Analytics Engine: double ON for app: com.aasare.FileDownload2
backboardd[28] <Error>: HID: The 'Passive' connection 'FileDownload2' access to protected services is denied.
PDF downloaded
receivedData : (null)
receivedData : (null)
Succeeded! Received 0 bytes of data

2 个答案:

答案 0 :(得分:0)

您可能应该在某处实例化receivedData

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    receivedData = [NSMutableData data];
}

你应该追加收到的数据。

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

并且您正在下载文件两次,但是您完全放弃了第二次下载。

此代码块已下载并保存数据:

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://code.google.com/p/androidnetworktester/downloads/detail?name=1mb.txt"]];
    [NSURLConnection connectionWithRequest:request delegate:self];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:@"/Users/awsuser8/1.txt"];
    NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://code.google.com/p/androidnetworktester/downloads/detail?name=1mb.txt"]];
    [thedata writeToFile:localFilePath atomically:YES];

这在主线程上以同步方式发生。在下载过程中,应用程序不做任何其他事如果您的下载很大,或者连接速度很慢,您的应用可能会在启动之前终止。

不要这样做。将文件保存代码放入connectionDidFinishLoading:。这是处理网络请求的异步方式。这就是你应该如何处理与网络相关的一切。

此外,您要写入的文件不存在。 writeData:不会创建导演。您可能应该删除整个/Users...路径组件。或者自己创建。

e.g:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://code.google.com/p/androidnetworktester/downloads/detail?name=1mb.txt"]];
    [NSURLConnection connectionWithRequest:request delegate:self];
    return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    receivedData = [NSMutableData data];
}


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

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *directoyPath = [documentsDirectory stringByAppendingPathComponent:@"Users/awsuser8"];
    NSError *error;
    if (![[NSFileManager defaultManager] fileExistsAtPath:directoyPath]) {
        if (![[NSFileManager defaultManager] createDirectoryAtPath:directoyPath withIntermediateDirectories:YES attributes:nil error:&error]) {
            NSLog(@"Can't create directoy %@", error);
        }
    }
    NSString *localFilePath = [directoyPath stringByAppendingPathComponent:@"1.txt"];
    if (![receivedData writeToFile:localFilePath options:NSDataWritingAtomic error:&error]) {
        NSLog(@"Can't write file. %@", error);
    }
}

答案 1 :(得分:-1)

尝试更改为 didReceiveData ,如下所示:

if(!receivedData)
    [receivedData setData:data];
else
   [receivedData appendData:data];