Convert an NSURL to an NSString

IosObjective CSwiftNsstringNsurl

Ios Problem Overview


I have an app where the user can choose an image either from the built-in app images or from the iphone photo library. I use an object Occasion that has an NSString property to save the imagePath.

Now in the case of the built-in app images I do get the file name as an NSString an save in the [occasion imagePath]. But in the 2nd case where the user picks an image form the photo library I get an NSURL which I want to convert to an NSString to be able to save it in [occasion imagePath].

Is it possible to convert the NSURL to an NSString?

Ios Solutions


Solution 1 - Ios

In Objective-C:

NSString *myString = myURL.absoluteString;

In Swift:

var myString = myURL.absoluteString

More info in the docs:

Solution 2 - Ios

If you're interested in the pure string:

[myUrl absoluteString];

If you're interested in the path represented by the URL (and to be used with NSFileManager methods for example):

[myUrl path];

Solution 3 - Ios

Try this in Swift :

var urlString = myUrl.absoluteString

Objective-C:

NSString *urlString = [myURL absoluteString];

Solution 4 - Ios

Swift update:

var myUrlStr : String = myUrl.absoluteString

Solution 5 - Ios

I just fought with this very thing and this update didn't work.

This eventually did in Swift:

let myUrlStr : String = myUrl!.relativePath!

Solution 6 - Ios

You can use any one way

NSString *string=[NSString stringWithFormat:@"%@",url1];

or

NSString *str=[url1 absoluteString];

NSLog(@"string :: %@",string);

> string :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAAA1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif

NSLog(@"str :: %@", str);

> str :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAA-A1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif

Solution 7 - Ios

In Swift :- var str_url = yourUrl.absoluteString

It will result a url in string.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAliView Question on Stackoverflow
Solution 1 - IosRandallView Answer on Stackoverflow
Solution 2 - Iosviggio24View Answer on Stackoverflow
Solution 3 - IosberylliumView Answer on Stackoverflow
Solution 4 - IoskmiklasView Answer on Stackoverflow
Solution 5 - IosSpeedzView Answer on Stackoverflow
Solution 6 - IosShaik ThuphelView Answer on Stackoverflow
Solution 7 - Ioskangna sharmaView Answer on Stackoverflow