how to save my image into a database using sqlite? [closed] - swift

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am making an app where you can post an image and display it on another page. I want to save it to a database but I don't know the best way to do it.

you can save your image in document folder by using
func saveImage(image: UIImage) -> Bool {
guard let data = UIImageJPEGRepresentation(image, 1) ?? UIImagePNGRepresentation(image) else {
return false
}
guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
return false
}
do {
try data.write(to: directory.appendingPathComponent("fileName.png")!)
return true
} catch {
print(error.localizedDescription)
return false
}
}
and you can get it your image with this method :
func getSavedImage(named: String) -> UIImage? {
if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
return UIImage(contentsOfFile: URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named).path)
}
return nil
}

You can use Core data in swift to save Image.
Core Data is an object graph and persistence framework provided by Apple in the macOS and iOS operating systems.
By using Core data you can access sqlite database easily.
To save image in Sqlite Using Core Data See saving-picked-image-to-coredata

you save your image in device and save path of that image in Sqlite.
this link for how to save image in device Saving image and then loading it in Swift (iOS)

Related

Use Image in SwiftUI with either URL or Data without UIKit

I have downloaded an image in bytes (Data). I stored it with FileManager in the cache of the user's device. I was wondering if I could create an Image with either Data or a local URL, I am currently using UIImage but I want to support macOS.
Is there a full SwiftUI way of creating an Image with URL or Data without UIKit/UIImage?
if your question is about showing and image in macos, that you already have downloaded (and is in the cachesDirectory), then try something like this, to create an image from your image in bytes: (using NSImage for macos)
struct ContentView: View {
#State var img = NSImage()
var body: some View {
Image(nsImage: img)
.onAppear {
do {
// local file
let url = try FileManager.default
.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("kat") // <--- your file name here
.appendingPathExtension("png")
print("----> url: \(url)")
// even from the net
// let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/e/ef/Red-billed_gull%2C_Red_Zone%2C_Christchurch%2C_New_Zealand.jpg")!
if let nsimg = NSImage(contentsOf: url) { img = nsimg }
} catch {
print("\(error)")
}
}
}
}

Adding External Sqlite Database to iOS application using swift

I want to add my own Database named Photos.sqlite to my iOS application. I have the following code to open the database, but is this creating a database named Photos.sqlite, and not using my own?
func createDB() -> OpaquePointer?{
let filePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathExtension(path)
var db : OpaquePointer?
guard sqlite3_open(filePath.path, &db) == SQLITE_OK else {
print("error opening database")
sqlite3_close(db)
db = nil
return nil
}
return db
}
I am asking how would I use my own database within the application? Where would I put the file? I did a bit of research and it states the Photos.sqlite must be in documents but I do not think I need this since I will only be reading data from the database, I will not be inserting or updating the database in any way.

How do I save documents to the gallery? - Swift [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I transform the images contained in the UIImage array into gifs and save them in the simulator's files. How can I save it on the phone's gallery instead?
extension UIImage {
static func animatedGif(from images: [UIImage]) {
let fileProperties: CFDictionary = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]] as CFDictionary
let frameProperties: CFDictionary = [kCGImagePropertyGIFDictionary as String: [(kCGImagePropertyGIFDelayTime as String): 1.0]] as CFDictionary
let documentsDirectoryURL: URL? = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL: URL? = documentsDirectoryURL?.appendingPathComponent("animated.gif")
if let url = fileURL as CFURL? {
if let destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, images.count, nil) {
CGImageDestinationSetProperties(destination, fileProperties)
for image in images {
if let cgImage = image.cgImage {
CGImageDestinationAddImage(destination, cgImage, frameProperties)
}
}
if !CGImageDestinationFinalize(destination) {
print("Failed to finalize the image destination")
}
print("Url = \(fileURL)")
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
UIImage.animatedGif(from: [UIImage(imageLiteralResourceName: "secilmemisstep"), UIImage(imageLiteralResourceName: "secilmisstep"), UIImage(imageLiteralResourceName: "secilmemisstep")])
}
Use UIImageWriteToSavedPhotosAlbum().

How to store pdf from a url in phone memory [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have pdf url, I want to know the code how to store that pdf in my phone memory. I want to store that pdf and want to view that pdf from phone. I am using swift 4 and Xcode for coding
Swift 4
Call this function only pass url and after downloading it will be return file url........
func get_file(httpUrl:String)
{
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let url = URL(string: httpUrl)!
let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = session.dataTask(with: request, completionHandler:
{
data, response, error in
if error == nil
{
if let response = response as? HTTPURLResponse
{
if response.statusCode == 200
{
if let data = data
{
if let _ = try? data.write(to: destinationUrl, options: Data.WritingOptions.atomic)
{
print(destinationUrl.absoluteString)
}
else
{
print(error!)
}
}
else
{
print(error!)
}
}
}
}
else
{
print(error!)
}
})
task.resume()
}
here you caught your file ..
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let url = URL(string: file_str)!
let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)

How To Add A Image In CoreData And How to Save The Image In CoreData [duplicate]

This question already has answers here:
Saving Picked Image to CoreData
(2 answers)
Closed 4 years ago.
How to add an image in core data? The image type what that I have selected. And how to save the core data image. How can I add a image?
Step 1:- Save the image in Document Directory
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)
let newPath = path.appendingPathComponent("image.jpg") //Possibly you Can pass the dynamic name here
// Save this name in core Data using you code as a String.
let jpgImageData = UIImageJPEGRepresentation(image, 1.0)
do {
try jpgImageData!.write(to: newPath)
} catch {
print(error)
}
}}
Step:-2: Fetch the Image back from the Document Directory and display index path row wise in table view cell.
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("image.png") //Pass the image name fetched from core data here
let image = UIImage(contentsOfFile: imageURL.path)
cell.imageView.image = image
}
This is simple and More convenient Method