I'm making a very simple app that uses a UIWebView to display a pdf map that can be zoomed in on, panned, etc.
However, when creating a target url for the pdf, the pathForResource call isn't working right. This is my code:
var targetURL : NSURL = NSBundle.mainBundle().pathForResource(filename, ofType: type)
I get an error on the parentheses before "filename", that says Missing argument for parameter 'inDirectory' in call. I tried adding an argument for this:
var targetURL : NSURL = NSBundle.mainBundle().pathForResource(filename, ofType: type, inDirectory: "Map")
I don't know what to put for inDirectory, because I don't know what the directory is - I added the file to my project and it is in the same folder as my ViewController.swift file. Anyway, it doens't really matter, because I get the following error in the same place, Extra argument 'inDirectory in call.
What do I do?
pathForResource() does not return a NSURL object, but a String?. Declare your variable accordingly and it should work.
var targetURL : String? = NSBundle.mainBundle().pathForResource(filename, ofType: type)
Or, of course, if you would rather - just use URLForResource() instead.
var targetURL : NSURL? = NSBundle.mainBundle().URLForResource(filename, withExtension: type)
I was having this same problem. In my case it was because my variable (in your case type) needed to be unwrapped. Adding a bang ! made the error go away and made the code execute.
Related
Surprisingly i have not been able to find an answer to this despite many searching.
I have a file that has been cached, i can retrieve the cache directory and file name which i believe to be the url?
this is code to get the file and then play it
let cachedFilePath = getCachedFilePath.result as! String
audioFileURL = cachedFilePath
self.audioPlayerItem = AVPlayerItem(url: NSURL(string: audioFileURL!) as! URL)
This is what is returned if i print audioFileURL:
/Users/Genie/Library/Developer/CoreSimulator/Devices/A2FB00CE-B018-4FDF-9635-35FD6678DF8D/data/Containers/Data/Application/E18B5E89-B973-4277-AA5C-1378C69D80CD/Library/Caches/Parse/PFFileCache/7e4a8fc0eb37b655b859e4959f986da2_The%20Name%20of%20the%20Wind%2017-92.mp3
The player loads but it never plays, It just sits there spinning. so i am wondering if i am passing the url to the player correctly?
i read on one thread to use file:// before it but that didn't work.
In the place where you're creating an NSURL, you have the replace the argument name string to fileURLWithPath
Change
NSURL(string: audioFileURL!)
to
NSURL(fileURLWithPath: audioFileURL!)
Also, why are you casting NSURL to URL ? Why not use URL directly?
try like this,i hope it will work for you.
self.audioPlayerItem = AVPlayerItem(url:NSURL(fileURLWithPath: audioFileURL!) as! URL)
AVPlayerItem(url:URL(fileURLWithPath: Bundle.main.path(forResource: "filename", ofType: "mp4")!))
And make sure your video is added to the bundle:
project root > your Target > Build Phases > Copy Bundle Resources.
let cStringRef : CFStringRef = CFStringCreateWithCString(nil, NSBundle.mainBundle().pathForResource("Luffy", ofType: "mp3")! , kCFStringEncodingMacRoman)
this encoding isn't working, though it is present in the Documentation.
to get MacRoman, I used CFStringGetSystemEncoding()
My question is how to retrieve a CFStringEncoding other than this.
If you just want to convert the path of Luffy.mp3 to CFString, use this:
let cStringRef = NSBundle.mainBundle().pathForResource("Luffy", ofType: "mp3")! as CFString
Edit: if you want to go the long way:
let path = NSBundle.mainBundle().pathForResource("Luffy", ofType: "mp3")!
let cString = path.cStringUsingEncoding(NSMacOSRomanStringEncoding)!
let cfString = CFStringCreateWithCString(nil, cString, CFStringBuiltInEncodings.MacRoman.rawValue)
That code doesn't make any sense whatsoever.
The path is an NSString, directly compatible with String and with CFStringRef. There is no C string in sight anywhere.
I really recommend that you figure out why on earth you want to use a CFString (which is more than unusual) and remove that usage. Or if you have been copying some code from the internet go and find some newer code to copy. If your Swift code uses a CFStringRef, you are doing something WRONG.
I am using an AVQueuePlayer to play local audio files which I have added to my Xcode project by dragging and dropping the .mp3 files into my folder in the project navigator pane. I then use this code to search thru my files and extract the files that I want, which I then use to fill a table view and to create AVPlayerItems for to play in my AVQueuePlayer.
My code works fine when I run the app on simulator but when i run the app on my iPhone, an error occurs and returns
fatal error: unexpectedly found nil while unwrapping an Optional value
Here is the code causing the issue...
var songNameArray: Array<String> = [String]()
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath("/Users/UsersName/Desktop/Xcode Projects Folder/LocalAudioFilePlayer/LocalAudioFilePlayer")!
while let element = enumerator.nextObject() as? String {
if element.hasSuffix("mp3") {
songNameArray.append(element)
print(element)
}
}
Are the files not being properly copied into the bundle which is then deployed to the iPhone? If so, what is the proper way to add the audio files?
I also tried this...
var songNameArray: Array<String> = [String]()
let path = String(NSBundle.mainBundle().resourcePath)
let songFiles = try! NSFileManager.defaultManager().contentsOfDirectoryAtPath(path)
for item in songFiles {
if item.hasSuffix("mp3"){
songNameArray.append(item)
print("appended to songNameArray \(item)")
}
}
But I get the error
The folder “LocalAudioFilePlayer.app")” doesn’t exist
Any help is greatly appreciated
let path = String(NSBundle.mainBundle().resourcePath)
This line is not doing what you might think it does. NSBundle.mainBundle().resourcePath returns String?, which is an optional type. When you create a string from that by wrapping String() around it, it doesn't unwrap the optional, it creates a string describing the optional, which looks like this:
Optional("/Users/markbes/Library/Developer/CoreSimulator/Devices/18D62628-5F8A-4277-9045-C6DE740078CA/data/Containers/Bundle/Application/3DDC064C-0DD1-4BE9-8EA4-C151B65ED1E1/Resources.app")
What you want there is something more like
var path = NSBundle.mainBundle().resourcePath!
That unwraps the String? type, and gives you a string (or throws an error).
Did you select "Copy files if needed" then dragged mp3s into Project?
Try to load files as following:
let path = NSBundle.mainBundle().pathForResource("filename", ofType: "ext")
let url = NSURL.fileURLWithPath(path!)
var audioPlayer: AVAudioPlayer?
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
} catch {
print("Unable to load file")
}
Note: use only filename here, not the whole path.
It sounds like you haven't added your sound file to your target in the Xcode project. If they don't "belong" to a target, they won't get copied into the "resources" folder during building.
Select the sound files you want to use in the project navigator, and check the file inspector (view->Utilities->File Inspector, and make sure that the appropriate target is selected under "target membership".
edit: this is definitely not the problem in this case. Leaving this answer, as it may be useful for others running into a similar issue.
I previously used below code to open up a dummy PDF, just for testing purpose, and now for the actual project i have to load a pdf based on the table cell clicked that will give the exact path of the pdf at some local path.
self.termsPath = NSBundle.mainBundle().pathForResource("DemoForm", ofType: "pdf")!
let url = NSURL(fileURLWithPath: termsPath!)
let pdfRequest = NSURLRequest(URL: url!)
pdfWebView.loadRequest(pdfRequest)
pdfWebView.scalesPageToFit = true
Now i have thisvariable docPath that will be passed from the prepareforSegue when table cell is clicked, i tried to use this variable in place of DemoForm but it gives below error
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0
Where i'm i going wrong here? Can anyone help me.Thanks
EDIT: By the way my docPath refers to something like ".../.../.../.../Referral.pdf"
I try to open a webpage with a IBAction
#IBAction func Start(sender: AnyObject) {
self.viewWebpage("http://www.xxxxx.xx")
}
func viewWebpage(webpage: String)
{
let url = NSURL.fileURLWithPath(webpage)
println(webpage)
let request = NSURLRequest(URL: url!)
self.viewPage.loadRequest(request)
// self.viewPage.reload()
}
The webpage i try to open works when i change in the function the the url to
let url = NSURL(string: "http://www.xxxxxx.xx")
Where is my mistake? The println() prints out the wright url
Issue is with:
let url = NSURL.fileURLWithPath(webpage)
You are converting the web url to file system url (url of a file contained in the system itself). So it won't work, you need to change that to:
let url = NSURL(string: webpage)
According to NSURL Class Reference
+ fileURLWithPath:
Initializes and returns a newly created NSURL object as a file URL
with a specified path. Declaration
Swift
class func fileURLWithPath(_ path: String) -> NSURL?
Objective-C
+ (NSURL *)fileURLWithPath:(NSString *)path
Parameters
path
The path that the NSURL object will represent. path should be a valid
system path. If path begins with a tilde, it must first be expanded
with stringByExpandingTildeInPath. If path is a relative path, it is
treated as being relative to the current working directory.
Passing nil for this parameter produces an exception.
Return Value
An NSURL object initialized with path.
Discussion
This method assumes that path is a directory if it ends with a slash.
If path does not end with a slash, the method examines the file system
to determine if path is a file or a directory. If path exists in the
file system and is a directory, the method appends a trailing slash.
If path does not exist in the file system, the method assumes that it
represents a file and does not append a trailing slash.
As an alternative, consider using fileURLWithPath:isDirectory:, which
allows you to explicitly specify whether the returned NSURL object
represents a file or directory.