ios - transfer In App将下载的文件下载到Document文件夹

时间:2014-04-29 09:03:34

标签: ios download in-app-purchase nsdocumentdirectory

我成功测试了我的应用内购买功能并下载了内容。但是,我不确定将其传输到Document文件夹的正确方法。我测试了代码:

    -(void)paymentQueue:(SKPaymentQueue *)queue updatedDownloads:(NSArray *)downloads
    {
        for (SKDownload *download in downloads)
        {
            switch (download.downloadState) {
                case SKDownloadStateActive:
                    NSLog(@"Download progress = %f",
                          download.progress);
                    NSLog(@"Download time = %f",
                          download.timeRemaining);
                    break;
                case SKDownloadStateFinished:

                    [self downloadFromURL:download.contentURL];///<--This is the function.
                    break;
            }
        }
    }

 -(void)downloadFromURL: (NSURL *) temporaryURL {

        NSString *folderName = [[temporaryURL path] lastPathComponent];
        NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *folder = [pathArr objectAtIndex:0];

        NSString *filePath = [folder stringByAppendingPathComponent:folderName];
        NSURL *fileURL = [NSURL fileURLWithPath:filePath];

        NSError *writeError = nil;
        NSData *downloadData = [[NSData alloc] initWithContentsOfURL:temporaryURL];
        [downloadData writeToURL: fileURL options:0 error:&writeError];

        if( writeError) {
            NSLog(@"Error in writing file %@' : \n %@ ", filePath , writeError);
            return;
        }
        NSLog(@"File successfully downloaded. Url is %@",fileURL.absoluteString);
        //myFileURL = fileURL;

        NSFileManager *filemgr;
        NSArray *filelist;
        int count;
        int i;

        filemgr =[NSFileManager defaultManager];
        filelist = [filemgr contentsOfDirectoryAtPath:folder error:NULL];
        count = [filelist count];
        NSLog(@"file count %i",count);
        for (i = 0; i < count; i++)
            NSLog(@"%@", filelist[i]);
    }

我从上面的代码中得到@"File successfully downloaded. Url is %@"NSLog(@"%@", filelist[i]);没有给我任何内容。这还缺少什么?我发现了this link 但不知道如何融入我的代码。任何指针都会很好。

1 个答案:

答案 0 :(得分:0)

让我们检查一下:

  -(void)downloadFromURL: (NSURL *) temporaryURL {
      // at this time, file is downloaded successfully???
      // I think you should check here
      NSURL * temporaryURL;
      NSFileManager *fm = [NSFileManager defaultManager];
      BOOL existed = [fm fileExistsAtPath:temporaryURL.path];
      if(existed) // file is existed 
      else        // file is not existed == maybe download fails
  }