我正在尝试使用swift safari服务开发safari扩展。该项目是从macos和safari扩展创建的。我是javascript开发人员,但开发safari扩展需要使用swift,但我不知道如何将数据保存在safari本地存储中。我看了下面的文件,但没有从中受益
https://developer.apple.com/documentation/safariservices/safari_app_extensions
这是代码
import SafariServices
class SafariExtensionViewController: SFSafariExtensionViewController {
@IBOutlet weak var passwordMessage: NSTextField!
@IBOutlet weak var emailMessage: NSTextField!
@IBOutlet weak var message: NSTextField!
@IBOutlet weak var email: NSTextField!
@IBOutlet weak var password: NSSecureTextField!
static let shared = SafariExtensionViewController()
override func viewDidLoad() {
self.preferredContentSize = NSSize(width: 300, height: 250)
message.stringValue = ""
emailMessage.stringValue = ""
passwordMessage.stringValue = ""
}
@IBAction func userLogin(_ sender: Any) {
let providedEmailAddress = email.stringValue
let providedPassword = password.stringValue
let isEmailAddressValid = isValidEmailAddress(emailAddressString: providedEmailAddress)
self.message.stringValue = ""
emailMessage.stringValue = ""
passwordMessage.stringValue = ""
if isEmailAddressValid && providedPassword.count > 0 {
let parameters = ["email": providedEmailAddress, "password": password.stringValue]
let URI = URL(string: "https://api.production.navihq.com/auth/sign_in")
let session = URLSession.shared
var request = URLRequest(url: URI!)
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
if let httpResponse = response as? HTTPURLResponse {
if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
self.message.stringValue = "Login Successful"
// i want to store the email in safari local storage here
} else {
self.message.stringValue = "Invalid Credentials"
}
}
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
} else {
emailMessage.textColor = NSColor.red
emailMessage.stringValue = "Invalid Email"
}
}
}
不是:我没有使用IOS。我正在使用狩猎服务。
认为您应该在Safari应用程序扩展和注入的脚本之间使用消息传递功能。例如,当DOMContentLoaded
触发时,将注入的脚本中的消息发送到应用程序ext.,并将所需数据(当前为电子邮件)发送给它,以通过注入的JS设置到浏览器的本地存储中。
希望它能有所帮助!