How to Convert Nsurl to String in Swift

How to convert NSURL to String in Swift

It turns out there are properties of NSURL you can access (see Swift Reference):

var directoryURL: NSURL
var urlString: String = directoryURL.absoluteString
// OR
var urlString: String = directoryURL.relativeString
// OR
var urlString: String = directoryURL.relativePath
// OR
var urlString: String = directoryURL.path
// etc.

How to convert NSURL to String

If you already have self.videoFilePath as NSURL, you don't have to convert it to String and then NSURL

To keep the code safer:

if let path = info[UIImagePickerControllerMediaURL] as? NSURL {
self.videoFilePath = path
let url = path
//Continue whatever you want
}

Converting URL to String and back again

fileURLWithPath() is used to convert a plain file path (e.g. "/path/to/file") to an URL. Your urlString is a full URL string including the scheme, so you should use

let url = NSURL(string: urlstring)

to convert it back to NSURL. Example:

let urlstring = "file:///Users/Me/Desktop/Doc.txt"
let url = NSURL(string: urlstring)
println("the url = \(url!)")
// the url = file:///Users/Me/Desktop/Doc.txt

how to convert url to string in ios/swift?

to convert url to string use this

var myurl: NSURL
var urlString: String = myurl.absoluteString

hope it helps

How to convert NSUrl to NSString?

Is it possible to convert NSUrl in to NSString for video file path.

Yes. Send it an absoluteString message.

i have try to use NSString *path = [ExportoutputURL absoluteString]; but it crash.

If you want a path, send the URL a path message. A string representing a URL is generally not a valid path; if you want a path, ask it for one.

As for the crash, it does not mean absoluteString is wrong. Sending absoluteString to an NSURL object is the correct way to get an NSString object that represents the URL. The problem is somewhere else.

Error EXC_BAD_ACCESS at

NSString *path = [ExportoutputURL absoluteString];

This probably means that ExportoutputURL points to something that is not nil but is also not a valid object. It might have pointed to an NSURL object at some point, but it doesn't now.

My guess would be that the problem is this:

ExportoutputURL = session.outputURL;

You assign the URL to the ExportoutputURL instance variable, but you don't retain the object or make your own copy. Therefore, you don't own this object, which means you are not keeping it alive. It may die at any time, most probably after this method (exportDidFinish:) returns.

The crash is because you call uploadVideoFile later, after the URL object has already died. You still have a pointer to it, but that object no longer exists, so sending a message to it—any message—causes a crash.

There are three simple solutions:

  1. Retain the URL object when you assign it to your instance variable.
  2. Make your own copy of the URL object and assign that to the instance variable.
  3. Declare ExportoutputURL as a property, with either the strong keyword or the copy keyword, and assign the object to the property, not the instance variable. That will call the property's setter, which, if you synthesize it or implement it correctly, will retain or copy the URL for you.

Either way, you will own the object, and that will keep it alive until you release it. Accordingly, you will need to release it when you are done with it (in dealloc, if not earlier), so that you don't leak it.

This all assumes that you are not using ARC. If you are using Xcode 4.2 or later, and can require iOS 4 or later, you should migrate your project to ARC, as it makes so many things much simpler. You would not need to retain or copy this object if you were using ARC, which means that migrating to ARC now is a fourth solution (but certainly a larger-scale one).

Convert an NSURL to an NSString

In Objective-C:

NSString *myString = myURL.absoluteString;

In Swift:

var myString = myURL.absoluteString

More info in the docs:

Converting [NSURL] into [String] for NSUserDefaults?

Using NSData

You can convert each NSURL to NSData in order to save it

func save(urls: [NSURL]) {
let urlsData = urls.map { $0.dataRepresentation }
NSUserDefaults.standardUserDefaults().setObject(urlsData, forKey: "urlsData")
}

Later on you can retrieve the NSData array and convert it back to [NSURL]

func load() -> [NSURL]? {
let retrievedData = NSUserDefaults.standardUserDefaults().arrayForKey("urlsData") as? [NSData]
return retrievedData?.map { NSURL(dataRepresentation: $0, relativeToURL: nil) }
}

Using String

Alternatively you can save the urls as String(s)

func save(urls: [NSURL]) {
let urlsData = urls.map { $0.absoluteString }
NSUserDefaults.standardUserDefaults().setObject(urlsData, forKey: "urlsData")
}

func load() -> [NSURL?]? {
let retrievedData = NSUserDefaults.standardUserDefaults().arrayForKey("urlsData") as? [String]
return retrievedData?.map { NSURL(string: $0) }
}

As discussed in the comments below, if data is written to NSUserDefaults exclusively with the save function, we know that every element of the array is a String representing a valid NSURL.

So we can change the return type of load from [NSURL?]? to [NSURL]? using this alternate version of load.

func load() -> [NSURL]? {
let retrievedData = NSUserDefaults.standardUserDefaults().arrayForKey("urlsData") as? [String]
return retrievedData?.flatMap { NSURL(string: $0) }
}

How to convert NSURL to String

If you already have self.videoFilePath as NSURL, you don't have to convert it to String and then NSURL

To keep the code safer:

if let path = info[UIImagePickerControllerMediaURL] as? NSURL {
self.videoFilePath = path
let url = path
//Continue whatever you want
}

Convert String to NSURL is return nil in swift

As suggested by the Martin R, I see THIS post and I converted that objective-c code to swift and I got this code:

var url : NSString = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitud‌​e),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US" 
var urlStr : NSString = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
var searchURL : NSURL = NSURL(string: urlStr)!
println(searchURL)

and this is working correctly.

For swift 3.0:

let url : NSString = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitud‌​e),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US"
let urlStr : NSString = url.addingPercentEscapes(using: String.Encoding.utf8.rawValue)! as NSString
let searchURL : NSURL = NSURL(string: urlStr as String)!
print(searchURL)


Related Topics



Leave a reply



Submit