NSUrl from NSString returns null

匿名 (未验证) 提交于 2019-12-03 01:14:02

问题:

I want to parse the location of my Documents Directory to NSUrl from NSString I have.

when my console NSLog(stringURL)

i get: "/var/mobile/Applications/2B35D06D-6E4A-40F2-833E-28463A946834/Library/Application Support/MyAppDirectory" as an output. 

but when I do

NSURL* url = [NSURL URLWithString:stringUrl]; 

and NSLog(url) i get (null) as an output.

WHat am I doing wrong here?

回答1:

From the apple documentation "An NSURL object initialized with URLString. If the URL string was malformed or nil, returns nil." Your stringURL isn't a correct formed url. For reference: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/clm/NSURL/URLWithString:

What you actually want to use is: fileURLWithPath: isDirectory: instead.

NSURL *url = [NSURL fileURLWithString:[stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] isDirectory:YES]; NSLog(@"%@", url); 


回答2:

How about:

NSURL* url = [NSURL fileURLWithString:stringUrl]; //                  ^^^^ 


回答3:

Use fileURLWithPath instead (since you are passing a file path):

NSURL* url = [NSURL fileURLWithPath:stringUrl]; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!