我正在使用一个名为"SQLClient"的库,位于:https://github.com/martinrybak/SQLClient
访问位于服务器上的数据库。安装库、pod 等后,我尝试制作一个 objective-c 头文件,并将示例代码示例放入文件中以测试是否有错误,但 IDE 给了我语法错误。
这是我刚刚放入应用程序的示例代码:
SQLClient* client = [SQLClient sharedInstance]; //initializer element is not a compile time constant
[client connect:@"serverinstance:port" username:@"user" password:@"pass" database:@"db" completion:^(BOOL success) { //expected identifier or '('
if (success) {
[client execute:@"SELECT * FROM Users" completion:^(NSArray* results) {
for (NSArray* table in results) {
for (NSDictionary* row in table) {
for (NSString* column in row) {
NSLog(@"%@=%@", column, row[column]);
}
}
}
[client disconnect];
}];
}
}]; // expected ']'
我在带有 IDE 给我的错误行旁边添加了注释。
以下是完整列表:
- 初始值设定项元素不是编译时常量
- 预期标识符或"(">
- 预期的"]">
- 消息发送表达式开头缺少"[">
任何建议将不胜感激
以下解决方案适用于Swift 5
.您需要将#import "SQLClient.h"
添加到桥接头文件。
podfile
use_frameworks!
platform :ios, '9.0'
install! 'cocoapods'
target 'SQLClient' do
use_frameworks!
pod 'SQLClient', '~> 1.0.0'
end
ViewController
文件如下所示,
override func viewDidLoad() {
super.viewDidLoad()
//Adding the observer for error and to receive the message
NotificationCenter.default.addObserver(self, selector: #selector(error(_:)), name: NSNotification.Name.SQLClientError, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(message(_:)), name: NSNotification.Name.SQLClientMessage, object: nil)
let client = SQLClient.sharedInstance()!
client.connect("ServerNameOrIP", username: "cool", password: "cool", database: "database") { success in
client.execute("SELECT * FROM table", completion: { (_ results: ([Any]?)) in
for table in results as! [[[String:AnyObject]]] {
for row in table {
for (columnName, value) in row {
print("(columnName) = (value)")
}
}
}
client.disconnect()
})
}
}
@objc func error(_ notification: Notification?) {
let code = notification?.userInfo?[SQLClientCodeKey] as? NSNumber
let message = notification?.userInfo?[SQLClientMessageKey] as? String
let severity = notification?.userInfo?[SQLClientSeverityKey] as? NSNumber
if let code = code, let severity = severity {
print("Error #(code): (message ?? "") (Severity (severity))")
}
}
@objc func message(_ notification: Notification?) {
let message = notification?.userInfo?[SQLClientMessageKey] as? String
print("Message: (message ?? "")")
}
在此处创建了一个示例项目