NSString to NSURL?

被刻印的时光 ゝ 提交于 2019-12-04 01:34:59
Dimme

This is how you create an NSURL from an NSString:

NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
swapnali patil

You can use following for creating the file path to url.

NSURL *yourURL = [NSURL fileURLWithPath:@"/Users/xyz/Desktop/abc.sqlite"];

If foundCode.barcodeString is the string you want as your URL, then (like the above answer) use the NSURL class method URLWithString:(NSString *).

Your code should look like:

NSURL urlToGrab = [NSURL URLWithString:foundCode.barcodeString];

Where is your error coming into to play? The way your code is, urlToGrab is an instance of NSString. I would imagine you would get an error like you described if you tried to make an HTTP request on an NSString rather than NSURL.

kirkgcm

Swapnali patil's answer works, but I will add an explanation.

You will get a nil if the format of NSString doesn't fit file criteria for NSURL (file:///xxx/file.ext).

My needs were with loading a JPG image via URL file path to nsdata; NSURL * u=[[NSURL alloc] initWithString:fpath] returned nil, but NSURL *yourURL = [NSURL fileURLWithPath:fpath] as in mentioned answer worked. A URL for files will be file:///users/xxx/pic.jpg format and give disk access. NSURL * u=[[NSURL alloc] initWithString:(NSString*) ] will also give nil object if nsstring is web URL but if missing http://

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