2016-07-21 74 views
0

我正在從JSON保存PDF。當我瀏覽到在App文件目錄的文件路徑,以驗證我有正確的文件,並嘗試打開PDF,我無法打開PDF,我得到這個錯誤:將PDF保存爲文檔(PDF已損壞)

enter image description here

enter image description here

文件路徑是好的,該文件是存在的,但它只是被損壞或東西。我認爲這與NSData有關,但我不確定我做錯了什麼。有什麼想法嗎?謝謝!

的ViewController:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    NSLog(@"Downloading PDF Started"); 

    // Get selected PDF 
    NSString *pdfSelected = self.pdfArray[indexPath.row]; 
    NSLog(@"PDFSl: %@", pdfSelected); 
    NSData *pdfData = [NSData dataWithContentsOfURL:[NSURL URLWithString:pdfSelected]]; 
    NSLog(@"PDFData: %@", pdfData); 
    NSString *pdfPath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%ld.pdf",@"savedPDF", (long)indexPath.row]]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     [pdfData writeToFile:pdfPath atomically:YES]; 
     NSLog(@"PDF File Saved!"); 
     NSLog(@"PDF File Path: %@", pdfPath); 
     // Save PDF path in defaults for evaluation in Details 
     [defaults setObject:pdfPath forKey:@"cachedPDFPath"]; 
    }); 

}); 

JSON片段:

{ 
     "fname": "Nadene", 
     "lname": "Feehan", 
     "email": "[email protected]", 
     "phone": "(152) 555-5321", 
     "image": "http://logok.org/wp-content/uploads/2014/04/Apple-logo-grey-880x625.png", 
     "video": "https://github.com/versluis/Movie-Player/blob/master/Movie%20Player/video.mov?raw=true", 
     "pdf": "http://adcdownload.apple.com/Developer_Tools/Xcode_8_beta_3/Release_Notes_for_Xcode_8_beta_3.pdf" 
    }, 

控制檯:

PDFSl:http://adcdownload.apple.com/Developer_Tools/Xcode_8_beta_3/Release_Notes_for_Xcode_8_beta_3.pdf

PDFDataLength: 2070

PDF File Path: /Users/user/Library/Developer/CoreSimulator/Devices/1/data/Containers/Data/Application/A/Documents/savedPDF0.pdf

我也試過:

NSData *pdfData = [NSData dataWithContentsOfURL:[NSURL URLWithString:pdfSelected] options:NSDataReadingUncached error:&errorPDF];但是當我檢查控制檯看到的錯誤是,如果你不與你的開發者帳戶登錄,沒有PDFDataError: (null)

+0

你能顯示控制檯日誌(具體地說,記錄語句的結果,你顯示)的內容是什麼?另外,當你記錄'PDFData'時,你還可以記錄數據的長度(即'pdfData.length')嗎?此外,如果沒有顯示任何有趣的內容,你可以嘗試使用'dataWithContentsOfURL:options:error:'來代替更簡單的'dataWithContentsOfURL:'來查看你是否真的並且成功地下載了數據。 – fullofsquirrels

+0

@fullofsquirrels沒問題,只是添加了控制檯日誌。你有什麼特別的嗎? – SRMR

+1

如果您未使用開發者帳戶登錄,網址就會被鎖定;當我試圖瓦特/出在第一已簽署,我重定向到這個網頁:https://developer.apple.com/unauthorized/ 你可能需要理清如何處理誰不簽約用戶到他們的開發者賬戶中(並且爲了使事情更加複雜,我相信,在20分鐘或一小時不活動之後,developer.apple.com會自動簽名),並且它看起來不像簡單的檢查那樣簡單HTTP狀態/錯誤代碼。 – fullofsquirrels

回答

1

貌似網址被鎖定;當我嘗試使用首次登錄時,我將重定向到此頁面:developer.apple.com/unauthorized。正如你所期望的那樣,內容是純粹的HTML,而且我猜測許多(如果不是絕大多數的話)PDF解析器會在發送HTML時崩潰。

你可能需要理清如何處理誰不簽入自己的開發者帳戶(用戶,使事情變得更加複雜,我相信developer.apple.com自動跡象,你出像20後幾分鐘或一小時不活動),並且它看起來不像簡單地檢查HTTP狀態/錯誤代碼那樣簡單。