19

Trying to convert a string to NSURL and this is not happening.

barcodeTextLabel.text = foundCode.barcodeString; urlToGrab = [NSString stringWithFormat:@"%@", foundCode.barcodeString]; // foundCode.barcodeString is an NSString 

urlToGrab shows the following "error invalid CFStringRef"

2
  • CAn u give ur code with some more details like urlToGrab belongs to Wat kind of DataType Commented Nov 14, 2011 at 3:46
  • 3
    How do you expect to get a NSURL from the +stringWithFormat: method? Commented Nov 14, 2011 at 3:51

4 Answers 4

57

This is how you create an NSURL from an NSString:

NSURL *url = [NSURL URLWithString:@"https://www.google.com"]; 
Sign up to request clarification or add additional context in comments.

1 Comment

NSURL is an object, so you are missing the *. NSURL *url
3

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

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

Comments

0

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.

Comments

-2

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://

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.