There are many examples on how to use imageWithContentsOfFile in object-c, but how do I use it in Swift. imageView.image = UIImage(imageWithContentsOfFile: imageName)
returns Argument labels '(imageWithContentsOfFile:)' do not match any available overloads
while if I write: imageView.image = UIImage(contentsOfFile:imageName)
It doesn't display the image.
(I have all images stores in Media.xcassets)
I am displaying a lot of images so using UIImage(named:imageName) isn't a viable option. How can I get the functionality of contentsOfFile in swift?
Swift code:
func getImage (named name : String) -> UIImage?
{
if let imgPath = Bundle.main.path(forResource: name, ofType: ".png")
{
return UIImage(contentsOfFile: imgPath)
}
return nil
}
//Image name "MyImage.png"
getImage(named: "MyImage")!
Related
Hey I am trying to retrieve the user image saved in the firebase storage but I am using this storage path (the folder of profile pictures in firebase) as a string(child path) to update the user image. When the user profile updates there are no errors this code just didn't update the user image as I expected what am I missing here that will allow me to successfully my user image and solve my problem ?
var spaceRef = Storage.storage().reference()
let storagePath = "gs://tunnel-vision-bc055.appspot.com/images/space.jpg"
spaceRef = Storage.storage().reference(forURL: storagePath)
let reference = spaceRef.child("profilePic")
// UIImageView in your ViewController
let imageView: UIImageView = self.ProfileImage
// Placeholder image
let placeholderImage = UIImage(named: "image/jpeg")
// Load the image using SDWebImage
imageView.sd_setImage(with: reference, placeholderImage: placeholderImage)
// Uh-oh, an error occurred!
return
}
This will not be the answer to all your issues, but hopefully some of them.
First of all, in Swift, variables and constants starts with a lowercase letter. Classes with uppercase. For example, your ProfileImage should be profileImage. For clarity, when I type profileImage I refer to your ProfileImage.
Now, types. You have a constant profileImage in the code you posted. This is of type String. You set the value of the key "ProfileImageUrl" to it. I would change it's name to profileImageURL.
Then (according to one of your comments) you are calling self.profileImage
let imageView: UIImageView = self.profileImage
Since you're not seeing any errors I assume you also have a class property called profileImage of type UIImageView.
The line
// let user = User(ProfileImage: ProfileImage)
will not help you. As far as I understand from the code you posted - and what you are trying to achieve - you may as well delete it. Or comment it (//) as I did above.
What you want to do is to set an imageView's image.
For this you need to do
imageView.image = image
And to be able to do that you need an imageView and an image. If you don't know how to create an imageView, search for answers here on SO.
You can then create the image from the url you get from Firebase and set it to the imageView. Kind of like this
let profileImageURL = value?["ProfileImageUrl"] as? String ?? ""
let url = URL(string: profileImageURL)
DispatchQueue.global().async {
guard let data = Data(contentsOf: url) else {return} // if url is nil, return block is executed and code below is not
DispatchQueue.main.async {
self.imageView.image = UIImage(data: data)
}
}
When the user selects an item from their photo library, the app saves the UIImage to the app's directory using the following code:
let imageUUID = UUID()
let filename = getDocumentsDirectory().appendingPathComponent("\(imageUUID)")
guard let uiImage = newImage else { return}
if let jpegData = uiImage.jpegData(compressionQuality: 0.8) {
try? jpegData.write(to: filename, options: [.atomicWrite, .completeFileProtection])
}
How can I use the saved image in a view?
Thanks!
First, you should save the UUID somewhere so that you can read the file later. This could be in UserDefaults, a JSON file, CoreData, or whatever, depending on your needs.
Suppose you have the path to the file stored in filePath, you can create an Image like this:
Image(uiImage: UIImage(contentsOfFile: filePath) ?? UIImage())
This will use an empty image as fallback if it failed to read the file.
Following code convert UIImage to Image in SwiftUI:
let uiImage = UIImage(contentsOfFile: path) ?? UIImage() // Access it from your storage
let image = Image(uiImage: uiImage)
There are different UIImage initializer methods available, you can use any one of them to get UIImage instance.
https://developer.apple.com/documentation/swiftui/image
You will like this tutorial of Coredata with SwiftUI: https://www.raywenderlich.com/9335365-core-data-with-swiftui-tutorial-getting-started
I am having the user take a photo with UIImagePickerController and I need it to be saved to the app so that it can be displayed when they need to see it later. How can I accomplish this?
I have heard NSUserDefaults would be a mistake. All I need to save is a single image, never more.
Here is the function to save your image to document folder
func saveImage (image: UIImage, path: String ) -> Bool{
let pngImageData = UIImagePNGRepresentation(image)
//let jpgImageData = UIImageJPEGRepresentation(image, 1.0) // if you want to save as JPEG
let result = pngImageData.writeToFile(path, atomically: true)
return result
}
Here is the function to get your document directory path with image name
func fileInDocumentsDirectory(filename: String) -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! String
return documentsFolderPath.stringByAppendingPathComponent(filename)
}
Here is an example of how to use your image path
let imagePath = fileInDocumentsDirectory(myImageName)
And here is how you save your image to that folder
saveImage(image, path: imagePath)
Now the last part is to get your image, so use this function to get your image
func loadImageFromPath(path: String) -> UIImage? {
let image = UIImage(contentsOfFile: path)
if image == nil {
println("Image not available at: (path)")
}
return image
}
And here is how you use the above function
image = loadImageFromPath(imagePath)
imageView.image = image
Hope this helps you
I have a very large set of images to upload, and the best way to do that is to let my app do it for me. But after copy and pasting the code from Parse's docs, it doesn't work.
var image = NSData(contentsOfURL: NSURL(string: "XY1_EN_1.jpg")!)!
#IBAction func xyButton1(sender: AnyObject) {
for var i = 1; i < 147; i++ {
let imageData = UIImageJPEGRepresentation(image)
//ERROR on line above: Missing argument for parameter #2 in call
let imageFile = PFFile(name:"image.png", data:imageData)
var userPhoto = PFObject(className:"Cards")
userPhoto["imageName"] = "XY1_EN_1"
userPhoto["imageFile"] = imageFile
userPhoto.save()
}
}
What am I doing wrong?
There are two problems with the code. UIImageJPEGRepresentation(::) takes two parameters, a UIImage and a float. Right now you are calling UIImageJPEGRepresentation(_:) and giving it NSData. If you want to use that method to get NSData from an Image, you need to make self.image of UIImage type instead of NSData. Maybe init your variable image with UIImage(named: "imageName") if the image is bundled.
I am trying to retrieve an image saved using:
let pngData = UIImagePNGRepresentation(image)
let finalPath = filePath() // This method just create the path to save to.
saveImage(pngData, filePath: finalPath)
Later I want to retrieve this data and set the UIImageView of a UIButton. However when I use the following code, it just displays a completely blue image.
Here is the code:
let filePath = tempCard?.frontPhoto
let imgData = UIImage(contentsOfFile: filePath!)frontPhotoButton.setImage(imgData, forState: .Normal)
frontPhotoButton.setImage(imgData, forState: .Normal)
I am not sure why this is just showing a blue button.
Edit:
I have also tried:
let filePath = tempCard?.frontPhoto
let imageData = NSData(contentsOfFile: filePath!
let image = UIImage(data: imageData!)
frontPhotoButton.setImage(image, forState: .Normal)
Same result.
For anyone else who has a problem in the future setting the background image of a UIButton. Both of the above code snippets work to retrieve the image.
The Problem was, in interface builder my button was: Type - System. When I changed Type - Custom everything worked fine.
Use this method to retrieve image from document directory of an app
func loadImageFromPath() {
dispatch_async(dispatch_get_main_queue(), {
let fileManager = NSFileManager.defaultManager()
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var getImagePath = paths.stringByAppendingPathComponent("Image2.png")
if (fileManager.fileExistsAtPath(getImagePath))
{
println("FILE AVAILABLE AT \(paths)");
//Pick Image and Use accordingly
var imageis: UIImage = UIImage(contentsOfFile: getImagePath)!
let data: NSData = UIImagePNGRepresentation(imageis)
self.imgProfileView.image = UIImage(data: data)
self.imgProfileView.contentMode = UIViewContentMode.ScaleAspectFit
}
else
{
println("FILE NOT AVAILABLE");
}
});
}