2011-11-12 27 views
7

已解決(感謝Regexident)文件名NSString在空間中添加了不必要的%20

我有一個應用程序將PDF的文件路徑傳遞給自定義-(id)init init方法。它被添加到表中,當它被選中時,它會爲不存在的文件調用else語句:

- (void) gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index { 

NSLog (@"Selected theArgument=%d\n", index); 

UIViewController *viewController = [[[UIViewController alloc]init]autorelease]; 
{ 
    //if file is built-in, read from the bundle 
    if (index <= 3) 
    { 
     // first section is our build-in documents 
     NSString *fileURLs = [_documentIconsURLs objectAtIndex:index]; 
     NSLog(@"file url -%@", fileURLs); 
     viewController = [[[xSheetMusicViewController alloc]initWithContentURL:fileURLs]autorelease]; 
    } 
    //if file is external, read from URL 
    else 
    { 
     // second section is the contents of the Documents folder 
     NSString *fileURL = [_documentIconsURLs objectAtIndex:index]; 
     NSLog(@"file url -%@", fileURL); 
     NSString *path; 
     NSString *documentsDirectoryPath = [self applicationDocumentsDirectory]; 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     path = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileURL]; 


     if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectoryPath]) 
     { 
      viewController = [[[xSheetMusicViewController alloc]initWithDocumentURL:fileURL]autorelease]; 
     } 
     else 
     { 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure!"               message:@"The Selected File Does Not Exist" 
                  delegate:nil 
                cancelButtonTitle:@"OK" 
                otherButtonTitles: nil]; 
      [alert show]; 
      [alert release];   
      return; 
     } 
    } 
[self.navigationController setNavigationBarHidden:YES animated:NO]; 
[UIView beginAnimations:@"animation" context:nil]; 
[UIView setAnimationDuration:1]; 
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.navigationController.view cache:YES]; 
[self.navigationController pushViewController:viewController animated:NO]; 
[UIView commitAnimations]; 
    } 
} 

因此,每當我的文檔中沒有空格時,它就會推送並進入。但是當文件名中有空格時,它表示它不存在。當我刪除if-else方法時,它會初始化,但崩潰因爲文件不存在。我試圖用常規空格替換文件路徑中的%20,但該方法繼續調用else部分。

那麼,文件路徑是不標準化和可讀的,還是我的其他方法錯了?

+0

通過代碼中的「%20」和變量命名(「... URL」)判斷,您將文件路徑(使用空格,等等)。 – Regexident

+0

將文件url從documentInteraction示例轉換爲apple方法中的字符串。雖然URL被傳遞給非DI控制器。那麼,我該如何解決它? – CodaFi

回答

16

當你的路徑似乎是個逃跑路徑字符串我想試試這個:

[fileURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] 

而且我重命名fileURLfileURLString明確指出,這是一個包含URL路徑一個NSString,而不是實際的NSURL(你的變量名稱會錯誤地暗示)。

但我會檢查填充_documentIconsURLs的代碼,因爲它可能是問題的根源。

+0

不錯的嘗試!但你先前的建議是正確的。我正在調用[filename lastpathcomponent]而不是[filename path];我仍然會投票給你。謝謝。 – CodaFi

相關問題