Swift: How to reference local image in NSURL - swift

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")

Related

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

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

How to use CFURLCreateFromFileSystemRepresentation with swift?

I am developing  with  audioQueueService 
But stop in function "CFURLCreateFromFileSystemRepresentation" 
here is my code but always get nil for return.
var path = Bundle.main.path(forResource: "123", ofType: "mp3")!
var xyz = UInt8(path.utf8CString[0])
let audioFileURL =  CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault,&xyz, path.characters.count, false)
print(audioFileURL)
I had try post path's point to func but not work?
can anyone help me?
let url = Bundle.main.url(forResource: "123", withExtension: "mp3")!
let audioFileURL = url as CFURL

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")

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")
}

How to get the URL of a selected image when using UIImapgePickerController with Swift?

The following code crashes because 'imageURLString' is NIL which I kind of understand. But playing around with objectForKey did not bring me to Eden either. Could someone please give me a kick...?
Thnx!
PHImageManager.defaultManager().requestImageDataForAsset(item, options: nil){
imageData,dataUTI,orientation,info in
let imageURLString = info!["PHImageFileURLKey"] as! String
let imageURL = NSURL(string: imageURLString)
print("imageURL: \(imageURL)")
}
info!["PHImageFileURLKey"] is exact NSURL. If you force cast to String. It will crash here. See this below code for fix that.
PHImageManager.defaultManager().requestImageDataForAsset(item, options: nil){
imageData,dataUTI,orientation,info in
let imageURL = info!["PHImageFileURLKey"] as! NSURL
//let imageURL = NSURL(string: imageURLString)
print("imageURL: \(imageURL)")
}
or safe code:
PHImageManager.defaultManager().requestImageDataForAsset(item, options: nil){
imageData,dataUTI,orientation,info in
if let _ = info {
// info will not nil here
if let imageURL = info!["PHImageFileURLKey"] as NSURL {
print("imageURL: \(imageURL)")
}
}
//let imageURL = NSURL(string: imageURLString)
//print("imageURL: \(imageURL)")
}
Hope that helps!
PHImageFileURLKey directly returns NSURL and that is what your issue. You are assuming it to be String.