Code refactor by using URLForResource method instead
of using the PathForResource method both in Obj-C and Swift
--
Currently, there are no code converters for converting Swift code into Obj-C code. If you have a project which is initially written in Obj-C and later a fork version of the same project is migrated into Swift. Code refactoring in both Obj-C and Swift can be quite tricky in case you started learning iOS app. development using Swift. In this article, I will be showing you how to refactor a code snippet both in Obj-C and swift.
The below code contains location of a file named “play.mp3” file which is being set to the constant path by using PathForResource method. The path constant is converted into a URL data type before setting it to constant playURL.
Obj-C
NSString *path = [[NSBundle mainBundle] pathForResource:@"play" ofType:@"mp3"];NSURL *playURL = [NSURL fileURLWithPath:path];
Swift
let path = Bundle.main.path(forResource: "play", ofType: "mp3")!let playURL = URL(fileURLWithPath: path)
The above code can be simplified by directly setting the file name “play.mp3” to the constant playURL by using the URLForResource method. [Note: If you have the files located in a directory (for example, Music) in your project. It is good to use the parameter — “sub-directory” and give the exact directory name].
Obj-C
NSURL *playURL = [[NSBundle mainBundle] URLForResource:@"play" withExtension:@"mp3" subdirectory:@"Music"];
Swift
let playURL = Bundle.main.url(forResource: "play", withExtension: "mp3", subdirectory: "Music")!
If you like my articles please follow me. You can also support me by https://www.buymeacoffee.com/akarshseggemu