Swift : read .vcf file from document directory? - swift

We get .vcf from Document directory path but can't import to the device using .vcf file URL like
'"Nik1 .vcf":
file:///Users/jksol-niketan/Library/Developer/CoreSimulator/Devices/18ADE140-22E4-4BEA-8C25-886AEE96C2CC/data/Containers/Data/Application/BC6A91A7-2920-4D5D-9787-F6D0E0DAB200/Documents/restore/Nik1%20.vcf'
How can solution for this file path URL to import iPhone device using swift/objective c
I tired of this issue, help with this query solution.
for r in restore{
var data: Data = Data()
do{
let url = URL(fileURLWithPath: r.value.path)
try data = NSData(contentsOf: url) as Data
var usersContact = [CNContact]()
do {
try usersContact = CNContactVCardSerialization.contacts(with: data)
} catch {
print("error")
}
let contact = usersContact[0]
print(contact)
}catch{
print("error")
}
}
Ex. restore = ["Nik1 .vcf":
file:///Users/jksol-niketan/Library/Developer/CoreSimulator/Devices/18ADE140-22E4-4BEA-8C25-886AEE96C2CC/data/Containers/Data/Application/BC6A91A7-2920-4D5D-9787-F6D0E0DAB200/Documents/restore/Nik1%20.vcf]

Related

Can't find the json file that I created

I used this code for encoding some data into a json file, but I can't really find the location of the file.
func save () {
let users: [UserCredentials] = []
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
do {
let data = try encoder.encode(users)
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("users.json")
try data.write(to: url)
} catch {
print("Error encoding JSON: \(error)")
}
}
I didn't find anything in the Document directory. Then I found out that I have to go to my Bundle ID that's located in library/application support, but I didn't find mine there.
Any idea where that json file is hiding?
Insert the line print(url.path) after the let url... line.
Run the code.
Copy (⌘C) the printed path in the console.
Switch to Finder, press ⇧⌘G, then ⌘V and return.

How do I add an Images folder to my FileWrapper

I need a FileWrapper which contains a file and contains a folder.
The file is a single file, and the folder is used to write images to.
The folder also can contain some subfolders. I have a working code, but the issue is that when the Document gets saved, the folder gets re-written which deletes my images and subfolders.
I'm quite sure it has something to do with func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper but I need some help from somebody with more experience with FileWrappers.
This is my code:
struct MyProject: FileDocument {
var myFile: MyFile
static var readableContentTypes: [UTType] { [.myf] }
init(myFile: MyFile = MyFile() {
self.myFile = myFile
}
init(configuration: ReadConfiguration) throws {
let decoder = JSONDecoder()
guard let data = configuration.file.fileWrappers?["MYFProject"]?.regularFileContents else {
throw CocoaError(.fileReadCorruptFile)
}
do {
self.myFile = try decoder.decode(MyFile.self, from: data)
} catch {
throw error
}
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let encoder = JSONEncoder()
do {
let data = try encoder.encode(myFile)
let mainDirectory = FileWrapper(directoryWithFileWrappers: [:])
let myfWrapper = FileWrapper(regularFileWithContents: data)
let imagesWrapper = FileWrapper(directoryWithFileWrappers: [:])
let imageSubFolder = FileWrapper(directoryWithFileWrappers: [:])
for numberString in myFile.numbers {
imageSubFolder.preferredFilename = numberString
imagesWrapper.addFileWrapper(imageSubFolder)
}
myfWrapper.preferredFilename = "MYFProject"
mainDirectory.addFileWrapper(myfWrapper)
imagesWrapper.preferredFilename = "MYFImages"
mainDirectory.addFileWrapper(imagesWrapper)
return mainDirectory
} catch {
throw error
}
}
}
I use this path to write images to.
func getSubFolderImageFolder(documentPath: URL, subFolder: String) -> URL {
let sfProjectPath = documentPath.appendingPathComponent("MYFImages").appendingPathComponent(subFolder)
if !FileManager.default.fileExists(atPath: sfProjectPath.path) {
do {
try FileManager.default.createDirectory(atPath: sfProjectPath.path, withIntermediateDirectories: false, attributes: nil)
return sfProjectPath
} catch {
fatalError(error.localizedDescription)
}
}
else {
return sfProjectPath
}
}
Thanks in advance!
Your getSubFolderImageFolder function is not going to work well with file wrappers. You must use the FileWrapper methods to create the folders and files in the file wrapper.
To add a subfolder to your images folder, create a directory file wrapper the same way you created the imagesWrapper folder for the images. Add the subfolder as a child of the images folder.
let imageSubFolder = FileWrapper(directoryWithFileWrappers: [:])
imagesWrapper.addFileWrapper(imageSubFolder)
You must create a directory file wrapper for each subfolder. I notice in your updated code, you have only one subfolder file wrapper. With only one subfolder file wrapper, you have no way to store an image file in the correct subfolder.
To add the images, start by converting each image into a Data object. Create a regular file wrapper for each image, passing the image data as the argument to regularFileWithContents. Call addFileWrapper to add the image file to the appropriate folder.
let imageFile = FileWrapper(regularFileWithContents: imageData)
imageFile.preferredFilename = "ImageFilename" // Replace with your filename.
imagesWrapper.addFileWrapper(imageFile)
In your case the image subfolders will call addFileWrapper to add the images. The destination for the image file calls addFileWrapper.
You can find more detailed information about file wrappers in the following article:
Using File Wrappers in a SwiftUI App

Swift: unzipping file

I’m trying to get String from txt file inside the zip file using native libcompression library. Actually I use the code from
https://github.com/mw99/DataCompression/blob/master/Sources/DataCompression.swift.
At first, I was doing:
let zip = try? Data(contentsOf: "/.../test.zip")
let tmp: Data? = zip?.unzip()
let txt: String? = String(data: tmp!, encoding: .utf8)
But how do I get the contents of zip file and how do I get data from certain txt file?
ZIP Foundation supports accessing individual entries in ZIP archives.
You have to initialize an archive by passing a file URL to the Archive initializer.
Afterwards you can access a specific entry via subscripting:
let fileManager = FileManager()
let currentWorkingPath = fileManager.currentDirectoryPath
var archiveURL = URL(fileURLWithPath: currentWorkingPath)
archiveURL.appendPathComponent("test.zip")
guard let archive = Archive(url: archiveURL, accessMode: .read) else {
return
}
guard let entry = archive["file.txt"] else {
return
}
var destinationURL = URL(fileURLWithPath: currentWorkingPath)
destinationURL.appendPathComponent("out.txt")
do {
try archive.extract(entry, to: destinationURL)
} catch {
print("Extracting entry from archive failed with error:\(error)")
}
You can also directly access the contents of entry by using the closure based API. This allows you to process the entry without writing it to the file system first:
try archive.extract(entry, consumer: { (data) in
print(data.count)
})

local file path won't import

I am trying to import the content of a .txt file to a string in my Xcode 9 project using Swift 4. When I use the full path name it imports successfully, current code:
let filePath = URL(fileURLWithPath: "/Users/main/Documents/ClaasPDI/PDIapp/PDIapp/holdMachines.txt")
do
{
machineString = try String(contentsOf: filePath)
}
catch
{
print("MACHINE INFORMATION DID NOT IMPORT")
}
I want to be able to import the data from the local path so it can be run on other computers besides mine. My swift files and holdMachines.txt are in the same folder PDIapp but when I change the code to:
let filePath = URL(fileURLWithPath: "holdMachines.txt")
it now crashes my app and says it could not access the file.
I also tried it with a / infront of the file name (below) but that also failed.
let filePath = URL(fileURLWithPath: "/holdMachines.txt")
How can I change my code to access the file through a local file path?
Put the text file in your Xcode project and use the following code to read it into a string:
let txtFile = Bundle.main.path(forResource: "holdMachines", ofType: "txt")
do {
let contents = try? String(contentsOfFile: txtFile!, encoding: .utf8)
} catch let err {
print(err.localizedDescription)
}

How to read and write images to web root directory in Perfect-Swift?

I have hosted a Perfect-Swift web application in a Ubuntu Linux server. I'm looking for a way to read an image file from the web root directory and convert it to base64 compatible string to send in the response.
I think something like this should work:
func yourHandler(request: HTTPRequest, _ response: HTTPResponse) {
let thisFile = File(Dir.workingDir.path + "21serfing.jpg")
if let bytes = try? thisFile.readSomeBytes(count: thisFile.size) {
let data = Data(bytes: bytes)
let base64Data = data.base64EncodedString()
response.appendBody(string: base64Data)
response.completed()
return
}
}
don't forget to import PerfectLib