Argument labels '(contentsOfFile:)' do not match any available overloads - swift

I'm updating my app with the new iOS 11 standards and a lot of stuff were deprecated and now I'm stacked with this error: "Argument labels '(contentsOfFile:)' do not match any available overloads.
Here you are the codes that was working:
//load plist file
var palermoip: NSArray?
if let path = Bundle.main.path(forResource: "palermoip", ofType: "plist") {
palermoip = NSArray(contentsOfFile: path)
}
Anyone knows how can I fix it? Thank you in advance !

I recommend to use PropertyListSerialization and the URL related API
let url = Bundle.main.url(forResource: "palermoip", withExtension: "plist")!
let data = try! Data(contentsOf:url)
let palermoip = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [[String:Any]] // or [Any] if the array does not contain dictionaries
and in Swift 4 even PropertyListDecoder

Related

How to start recoding a AVCaptureSession in Swift 3?

This is the method I'm trying to fire:
mMovieFileOutput?.startRecording(toOutputFileURL: URL(mov_path), recordingDelegate: self)
I'm getting this error:
Argument labels '(_:)' do not match any available overloads
Dose anyone know what arguments I need?
You need to use one of the valid initializers for URL.
Here is some basic Swift 3 code to demonstrate this.
var videoFileOutput = AVCaptureMovieFileOutput()
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let filename = NSUUID().uuidString + ".mov"
let filePath = documentsURL.appendingPathComponent(filename)
videoFileOutput.startRecording(toOutputFileURL: filePath, recordingDelegate: self)
If you want to use some other URL initializer for some reason, just use a valid one. As #Anton said, URL(fileURLWithPath: "") is correct initializer for a path.
Cheers

How to get user home directory path (Users/"user name") without knowing the username in Swift3

I am making a func that edits a text file in the Users/johnDoe Dir.
let filename = "random.txt"
let filePath = "/Users/johnDoe"
let replacementText = "random bits of text"
do {
try replacementText.write(toFile: filePath, atomically: true, encoding: .utf8)
}catch let error as NSError {
print(error: + error.localizedDescription)
}
But I want to be able to have the path universal. Something like
let fileManager = FileManager.default
let downloadsURL = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first! as NSURL
let downloadsPath = downloadsURL.path
but for the JohnDoe folder. I haven't been able to find any documentation on how to do this. The closest thing I could find mentioned using NSHomeDirectory(). And I am not sure how to use it in this context.
when I try adding it like...
let fileManager = FileManager.default
let downloadsURL = FileManager.default.urls(for: NSHomeDirectory, in: .userDomainMask).first! as NSURL
let downloadsPath = downloadsURL.path
I get an error:
"Cannot Convert value of type 'String' to expected argument type 'FileManager.SearchPathDirectory'"
I've tried it .NSHomeDirectory, .NSHomeDirectory(), NShomeDirectory, NShomeDirectory()
You can use FileManager property homeDirectoryForCurrentUser
let homeDirURL = FileManager.default.homeDirectoryForCurrentUser
If you need it to work with earlier OS versions than 10.12 you can use
let homeDirURL = URL(fileURLWithPath: NSHomeDirectory())
print(homeDirURL.path)
There should be an easier way but -- at worst -- this should work:
let filePath = NSString(string: "~").expandingTildeInPath
Swift 5 (and maybe lower)
let directoryString: String = NSHomeDirectory()
let directoryURL: URL = FileManager.default.homeDirectoryForCurrentUser
Maybe
FileManager.homeDirectoryForCurrentUser: URL
It's listed as "beta" for 10.12, though.

Load Url image from Plist in Swift

I have a plist running in my project which contains number of image urls.I am trying to pass the url image to my imageView which is in the same viewController.I found similar questions from github like Loading/Downloading image from URL on Swift , Swift - Read plist , Can't get plist URL in Swift I went through all those answers but no luck so far rather than fatal crash. My partial codes as follows....
Method 1:
override func viewDidLoad() {
super.viewDidLoad()
if let path = Bundle.main.path(forResource: "apps", ofType: "plist"),
let root = (NSArray(contentsOfFile: path))
{
let url = NSURL(string: path)
let data = NSData(contentsOf: url! as URL)
if let imageData = data {
imageView.image = UIImage(data: imageData as Data)
}
**// Swift Console Printinging as Follows**
print(root)
// printing all my plist url links like {icon = "https://xxxxxxxxxxx.com/image/girl_face_freckles_eyes_92358_1920x1080.jpg";}
print(url)
// (/Users/xxxxxx/Library/Developer/CoreSimulator/Devices/52DA3F73-83E0-4C29-9DE1-D8D5F0731C13/data/Containers/Bundle/Applica ... ps.plist)
print(data)
// nil
print(imageView.image)
//nil
} else {
print("Either the file does not exist or the root object is an array")
}
Method 2:
let path = Bundle.main.path(forResource: "apps", ofType: "plist")
let url = NSURL(string: path!)
let imgData = try? Data(contentsOf: url as! URL)
let img = UIImage(data: imgData!)!
print(img) // fatal crash
}
path is the path to your plist, not to your image URL.
The image URL is in the key "icon" in the "root" array.
Get the first item of the array and subscript with the key, you should get your image URL:
if let item = root[0] as? [String:Any] {
if let result = item["icon"] as? String {
print(result)
}
}
The path in (NS)Bundle is a file system path and these paths must be created with URL(fileURLWithPath:)
let path = Bundle.main.path(forResource: "apps", ofType: "plist")
let url = URL(fileURLWithPath: path!)
But why does nobody use the URL related API which is much more convenient
let url = Bundle.main.url(forResource: "apps", withExtension: "plist")

Swift: How to reference local image in NSURL

I have a code which loads some thumbnails from articles retrieved online and places them into an Article object. It looks like the following:
for article in newArticlesArray {
let url: String
if let myGroup = article["group"] as? Dictionary<NSObject, AnyObject>, let myThumbnail = myGroup["thumbnail"] as? Dictionary<NSObject, AnyObject>, let myURL = myThumbnail["url"] as? String{
url = myURL
}
else{
url = "file://no-thumbnail.png"
}
let a = Article(t: article["title"] as! String,
da: article["pubDate"] as! String,
de: newDesc,
th: NSURL(string: url)!,
l: NSURL(string: article["link"] as! String)!)
articlesArray.addObject(a)
However the issue arises when an article does not have a thumbnail and hence I have to use a local image. The local file for no thumbnail is called no-thumbnail.png, however I cannot seem to find a simple guide online on how to actually reference a local file, in this case a .png image, through the usage of an NSURL in swift.
Looking for somebody to share some insight into this.
Solution
For people interested the solution is as follows:
let th = NSBundle.mainBundle().URLForResource("no-thumbnail", withExtension: "png")
url = th!.absoluteString
You can use Bundle.main.url(forResource: "no-thumbnail", withExtension: "png")
The syntax has changed a bit for Swift 4:
let imageURL = Bundle.main.url(forResource: "imageName", withExtension: "png")

Can't get plist URL in Swift

I'm really confused on this one. There are dozens of questions around the web asking "How do I get info from my plist file in Swift?" and the same answer is posted everywhere:
let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist")
However, this line produces always produces nil for me. I have replaced Config with other components found in the default plist file, but get nil as well.
I am trying to access my custom ProductIdentifiers Array like so:
let url = NSBundle.mainBundle().URLForResource("ProductIdentifiers", withExtension: "plist")!
var productArray = NSArray(contentsOfURL: url) as! [[String:AnyObject!]]
I get a crash stating fatal error: unexpectedly found nil while unwrapping an Optional value on productArray. I have also tried this with other default plist values in place of ProductIdentifiers.
Does anyone know why this is not working for me even though there are so many posts around of people using this successfully?
I've never heard of the OP's approach working before. Instead, you should open the Info.plist file itself, then extract values from it, like so:
Swift 3.0+
func getInfoDictionary() -> [String: AnyObject]? {
guard let infoDictPath = Bundle.main.path(forResource: "Info", ofType: "plist") else { return nil }
return NSDictionary(contentsOfFile: infoDictPath) as? [String : AnyObject]
}
let productIdentifiers = getInfoDictionary()?["ProductIdentifiers"]
Swift 2.0
func getInfoDictionary() -> NSDictionary? {
guard let infoDictPath = NSBundle.mainBundle().pathForResource("Info", ofType: "plist") else { return nil }
return NSDictionary(contentsOfFile: infoDictPath)
}
let productIdentifiers = getInfoDictionary()?["ProductIdentifiers"]
Resource represents the file name of the plist rather than its contents.
The root object of the plist is probably a dictionary.
Replace MyPlist with the real file name.
This code prints the contents of the plist
if let url = NSBundle.mainBundle().URLForResource("MyPlist", withExtension: "plist"),
root = NSDictionary(contentsOfURL: url) as? [String:AnyObject]
{
print(root)
} else {
print("Either the file does not exist or the root object is an array")
}