Since I have updated to Xcode 7 and swift 2, I'm getting this errors:
No type named 'Query' in module 'SQLite'
Use of undeclared type 'Database'
using this code:
let table:SQLite.Query
init(db:Database){
table = db["BucketType"]
}
I'm using the swift2 branch of SQLite.swift, but it looks like my project, it can't find the reference SQLite.swift module.
Also have import SQLite on every file I use SQLite.swift with.
I've tried the manual integration and the cocoa pods, but with the same results.
It was working with Xcode 6.4.
I have something like this...
class DBHelper {
static let instance = DBHelper() // singleton
var db : Connection
init() {
do {
self.db = try Connection("\(Util.getDBPath())/db.sqlite3")
createTablesIfNotExists()
} catch {
Logger.error("Could not create a connection to database")
}
}
func createTablesIfNotExists() {
// Logs
let logs = Table(TLog.TABLE_NAME) // just the name of your table
do {
try db.run(logs.create(ifNotExists: true) { t in
t.column(TLog.ID, primaryKey: true) // Expression<Int>("id")
t.column(TLog.TS) // Expression<String>("ts")
t.column(TLog.TAG) // Expression<String>("tag")
t.column(TLog.TYPE) ...
t.column(TLog.CONTENT) ...
})
} catch {
Logger.error("Could not create table Logs")
}
}
And.. Util.getDBPath would be...
import SystemConfiguration
class Util {
class func getDBPath() -> String {
let path = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true
).first
return path!
}
}
Hope this help you.
Related
I'm new to CoreStore and attempting to test my ability to create, store, and fetch CoreStore Objects correctly. It appears entries are being created based on results of dataStack.fetchCount() and transaction.create(), but the data is unavailable or not stored correctly based on my results of dataStack.fetchAll() (it says data: fault at the end of each object) and inspection of the SQLite database with Liya software reveals no entries in the table. I'm using CoreStore v8.0.1 and Xcode v12.4. My example code (using synchronous execution) is below. I appreciate your input into troubleshooting the issue. Thanks.
MyImage.swift:
import CoreStore
final class MyImage: CoreStoreObject {
#Field.Stored("desc")
var desc: String = ""
}
MyApp.swift
import SwiftUI
import CoreStore
import Foundation
#main
struct MyApp: App {
static let dataStack: DataStack = {
let dataStack = DataStack(
CoreStoreSchema(
modelVersion: "V1",
entities: [
Entity<MyImage>("MyImage")
],
versionLock: [
"MyImage": [..., ..., ..., ...]
]
)
)
try! dataStack.addStorageAndWait(
SQLiteStore( fileName: "MyStore.sqlite",
//localStorageOptions: .allowSynchronousLightweightMigration,
localStorageOptions: .recreateStoreOnModelMismatch
)
)
print(dataStack.coreStoreDumpString)
return dataStack
}()
init() {
CoreStoreDefaults.dataStack = MyApp.dataStack
try! dataStack.perform(
synchronous: { (transaction) in
let test_obj = transaction.create(Into<MyImage>())
test_obj.desc = "Description"
},
waitForAllObservers: true
)
do {
let objects = try dataStack.fetchAll(From<MyImage>())
print(objects)
} catch { print("error fetching")}
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
I appreciate your help.
It turns out that the fetch results will display data:fault until the properties of the objects are accessed. The following example code will display the value of the properties:
let objects = try dataStack.fetchAll(From<MyImage>())
print(objects.map { $0.desc })
I have implemented a custom framework and it is integrated into a hyperloop enabled project.
I am passing function definitions as arguments to a swift function that takes a protocol.
Javascript:
var customListener = {};
customListener.onPayEvent = function(event) {
console.log("moop");
};
var PayView = require('Pay/PayView');
var payView = PayView.alloc().initWithPayEventListener(customListener);
This javascript function definition comes in as a KrollCallback.
Swift Code:
class PayListener: NSObject, WootPayEventListener {
let payEventListener: PayEventListener
init(payEventListener: PayEventListener) {
self.payEventListener = payEventListener
}
public func onPayEvent(PayEvent: PayEvent) {
os_log("calling payEventListener.onPayEvent")
os_log("listener description = %{public}#", self.payEventListener.description)
os_log("listener debugDescription = %{public}#", self.payEventListener.debugDescription ?? "")
// self.payEventListener.onPayEvent(payEvent: "woo dogggy")
}
}
How do I call methods on this object so that I can return the result from swift back to javascript?
I was able to do this by building the TitaniumKit framework locally and then importing it into my project.
The TitaniumKit source code is here: https://github.com/appcelerator/titanium_mobile/tree/master/iphone/TitaniumKit
The current build steps for the framework are below
carthage build --archive
Once I imported it into the project I was able to use KrollCallback like this:
class SimplePayListener: NSObject, SimplePayEventListener {
let payEventListener: PayEventListener
init(payEventListener: PayEventListener) {
self.payEventListener = payEventListener
}
public func onPayEvent(payEvent_ payEvent: String) {
os_log("SimplePayListener event description = %{public}#", fivestarsPayEvent.description)
let appceleratorCallback:KrollCallback = self.payEventListener as! KrollCallback
appceleratorCallback.call([payEvent], thisObject: self.payEventListener)
}
}
I am trying to make a Data-Storage using NSCoder, for some weird reason, its showing this error to me where i try to use the .encode keyword, please help me understand what i'm doing wrong..
let encoder = PropertyListEncoder()
do {
let data = try encoder.encode(self.itemArray) // <--- showing error here
} catch {
}
Never-mind, I found the problem! If you guys are facing the same problem where you make your array takes data specified in a class, you need to make the class 'Encodable' ie
import Foundation
class CellItemReg : Encodable { // <-- 'Encodable'
var done : Bool = false
var title : String = ""
}
This fixed for me in Swift iOS.
Inherit Codable in the class which you are trying to encode.
In your case,
let encoder = PropertyListEncoder()
do {
let data = try encoder.encode(self.itemArray) // <--- showing error here
} catch {
}
Let's assume itemArray is the array of a class named 'Item'. Then your 'Item' needs to inherit Codable in swift.
Just as below.
import Foundation
class Item: Codable {
var id: Int!
}
All the best!
I'm trying to test some sqlite database calls through XCode's playground. I start with a database in my Playground's Resources folder and try to move it to the Playgrounds Documents folder, however what happens is that a symbolic link is generated pointing back to the file within the Resources folder so I am unable to write to that file. However, If I figure out where the Documents folder is and then copy the file there by hand from the terminal everything works just fine.
So why does the file manager copy command actually create a sym link to rather than copy? And is there any way to actually make this happen? It seems to only be a problem with the Playground. copy from Resource to Documents works fine in the app itself.
some code to test within the playground...
let dirPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)
let docsDir = dirPaths[0]
let destPath = (docsDir as NSString).appendingPathComponent("/data.sqlite")
print(destPath)
let fileMgr = FileManager.default
let srcPath = Bundle.main.path(forResource: "data", ofType:"sqlite")
// This copies the data.sqlite file from Resources to Documents
// ** However in the playground, only a symlink is generated
do {
try fileMgr.copyItem(atPath: srcPath!, toPath: destPath)
} catch let error {
print("Error (during copy): \(error.localizedDescription)")
}
Rod, It's too late but, I figure this out.
Context:
I add one playground to my project in the same workspace
To make the playground works with my project, I create a framework
I added the Store.db file to the framework target
I haven't added the Store.db to the Playground as a Resource
Swift 3
Playground
#testable import MyAppAsFramework
func copyMockDBToDocumentsFolder(dbPath: String) {
let localDBName = "Store.db"
let documentPath = dbPath / localDBName
let dbFile = Bundle(for: MyAppAsFrameworkSomeClass.self).path(forResource: localDBName.deletingPathExtension, ofType: localDBName.pathExtension)
FileManager.copyFile(dbFile, toFolderPath: documentPath)
}
copyMockDBToDocumentsFolder(dbPath: "The documents path")
Things like / copyFile(x) and the others are operator overloads and extensions
extension String {
public var pathExtension: String {
get {
return (self as NSString).pathExtension
}
}
public var deletingPathExtension: String {
get {
return (self as NSString).deletingPathExtension
}
}
public func appendingPath(_ path: String) -> String {
let nsSt = self as NSString
return nsSt.appendingPathComponent(path)
}
}
infix operator / : MultiplicationPrecedence
public func / (left: String, right: String) -> String {
return left.appendingPath(right)
}
extension FileManager {
class func copyFile(_ filePath: String?, toFolderPath: String?) -> Bool {
guard let file = filePath else { return false }
guard let toFolder = toFolderPath else { return false }
var posibleError: NSError?
do {
try FileManager.default.copyItem(atPath: file, toPath:toFolder)
} catch let error as NSError {
posibleError = error
print("CAN'T COPY \(error.localizedDescription)")
}
return posibleError == nil
}
}
Currently I'm working on my new App written with Swift 2.0. Today I faced two strange errors in Xcode beta 5. I'd love if someone with a previous beta version of Xcode can confirm if I'm right or not. I also could misunderstand something, so I'll appreciate any feedback.
Here is some example code that made me struggle a while:
// Frist bug
protocol SomeProtocol {
var someArray: [String] { get set } // #1 bug
}
extension SomeProtocol {
func someFunction(someString: String) {
self.someArray.append(someString) // #1: Immutable value of type '[String]' only has mutating members named 'append'
}
}
// Second bug
protocol SomeInterfaceProtocol {
var someBool: Bool { get set } // #2 bug
}
class SomeClass: SomeInterfaceProtocol {
var someBool: Bool = false
func returnInterface() -> SomeInterfaceProtocol {
return self
}
}
let someInstance = SomeClass()
// can't set the value
someInstance.returnInterface().someBool = true // #2: Cannot assign to property: function call returns immutable value
The first error can be solved if you add the modifier mutating before the extension func declaration like this:
mutating func someFunction(someString: String) {
I suspect that's a change in the language.
The other one puzzles me as well. At least, here's a work-around:
var c = someInstance.returnInterface()
c.someBool = true
I think the second one isn't a bug as well for the same reason that you can't modify an item in a dictionary directly, or that you can't change elem in for elem in array { ... }.
Something has to be saved to be able to change it. Because you're returning the protocol type, the compiler can't know whether it's a struct or a class, whereas if it's a struct the operation of changing it would have no effect because it's not persisted in any way and structs aren't passed by reference. That's why Thomas' workaround works. Maybe it'll work too if returnInterface returned a class instance, instead of the protocol type.
EDIT: Just tried it out: Indeed it works either if you return SomeClass instead of SomeInterfaceProtocol or if you change the protocol to a class protocol, as it can't be a struct
protocol SomeInterfaceProtocol : class {
var someBool: Bool { get set }
}
class SomeClass: SomeInterfaceProtocol {
var someBool: Bool = false
func returnInterface() -> SomeInterfaceProtocol {
return self
}
}
or
protocol SomeInterfaceProtocol {
var someBool: Bool { get set }
}
class SomeClass: SomeInterfaceProtocol {
var someBool: Bool = false
func returnInterface() -> SomeClass {
return self
}
}
both work