Я надеюсь, что кто-то может помочь мне в решении этих ошибок. Я получаю свой проект Swift.Swift - Ошибки, которые я не могу решить
Я довольно новичок в кодировании приложений, поэтому, если мне кажется, что мы сожалеем заранее.
До сих пор я создал приложение со страницей входа и регистрации, которая все соединена вместе. Теперь я делаю часть кода, которая соединяет все это вместе.
Я использую систему управления пользователями под названием StormPath, и это так, как это делается.
LoginViewController.Swift
import UIKit
import Stormpath
class LoginViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBAction func login(_ sender: AnyObject) {
// Code when someone presses the login button
Stormpath.sharedSession.login(emailTextField.text!, password: passwordTextField.text!, completionHandler: openNotes)
}
@IBAction func loginWithFacebook(_ sender: AnyObject) {
// Code when someone presses the login with Facebook button
}
@IBAction func loginWithGoogle(_ sender: AnyObject) {
// Code when someone presses the login with Google button
}
@IBAction func resetPassword(_ sender: AnyObject) {
// Code when someone presses the reset password button
Stormpath.sharedSession.resetPassword(emailTextField.text!) { (success, error) -> Void in
if let error = error {
**self.showAlert(withTitle: "Error", message: error.localizedDescription)**
} else {
**self.showAlert(withTitle: "Success", message: "Password reset email sent!")**
}
}
}
func openNotes(success: Bool, error: NSError?) {
if let error = error {
**showAlert(withTitle: "Error", message: error.localizedDescription)**
}else {
performSegue(withIdentifier: "login", sender: self)
}
}
// Helper extension to display alerts easily.
**extension UIViewController {**
func showAlert(withTitle title: String, message: String?) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
RegisterViewController.Swift
import UIKit
import Stormpath
class RegisterViewController: UIViewController {
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: .exit)
}
func exit() {
dismiss(animated: true, completion: nil)
}
@IBAction func register(_ sender: AnyObject) {
// Code for registering the user
let newUser = RegistrationModel(email: emailTextField.text!, password: passwordTextField.text!)
newUser.givenName = firstNameTextField.text!
newUser.surname = lastNameTextField.text!
// Register the new user
Stormpath.sharedSession.register(newUser) { (account, error) -> Void in
if let error = error {
**self.showAlert(withTitle: "Error", message: error.localizedDescription)**
} else {
self.exit()
}
}
}
}
private extension Selector {
static let exit = #selector(RegisterViewController.exit)
}
NotesViewController.swift (все еще не закончили кодирование)
import UIKit
import Stormpath
class NotesViewController: UIViewController {
@IBOutlet weak var helloLabel: UILabel!
@IBOutlet weak var notesTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: .keyboardWasShown, name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: .keyboardWillBeHidden, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Place code to load data here
Stormpath.sharedSession.me { (account, error) -> Void in
if let account = account {
self.helloLabel.text = "Hello \(account.fullName)!"
}
}
var request = URLRequest(url: notesEndpoint)
request.setValue("Bearer \(Stormpath.sharedSession.accessToken ?? "")", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
guard let data = data, let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any], let notes = json["notes"] as? String else {
return
}
DispatchQueue.main.async(execute: {
self.notesTextView.text = notes
})
})
task.resume()
}
@IBAction func logout(_ sender: AnyObject) {
// Code when someone presses the logout button
Stormpath.sharedSession.logout()
dismiss(animated: false, completion: nil)
}
func keyboardWasShown(_ notification: Notification) {
if let keyboardRect = ((notification as NSNotification).userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue {
notesTextView.contentInset = UIEdgeInsetsMake(0, 0, keyboardRect.size.height, 0)
notesTextView.scrollIndicatorInsets = notesTextView.contentInset
}
}
func keyboardWillBeHidden(_ notification: Notification) {
notesTextView.contentInset = UIEdgeInsets.zero
notesTextView.scrollIndicatorInsets = UIEdgeInsets.zero
}
}
extension NotesViewController: UITextViewDelegate {
func textViewDidBeginEditing(_ textView: UITextView) {
// Add a "Save" button to the navigation bar when we start editing the
// text field.
**let postBody = ["notes": notesTextView.text]
var request = URLRequest(url: notesEndpoint)**
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: postBody, options: [])
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(Stormpath.sharedSession.accessToken ?? "")", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request)
task.resume()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: .stopEditing)
}
func stopEditing() {
// Remove the "Save" button, and close the keyboard.
navigationItem.rightBarButtonItem = nil
notesTextView.resignFirstResponder()
}
func textViewDidEndEditing(_ textView: UITextView) {
// Code when someone exits out of the text field
}
}
private extension Selector {
static let keyboardWasShown = #selector(NotesViewController.keyboardWasShown(_:))
static let keyboardWillBeHidden = #selector(NotesViewController.keyboardWillBeHidden(_:))
static let stopEditing = #selector(NotesViewController.stopEditing)
}
Теперь ошибки я имею являются:
- Декларация действительна только в файле объем
- Ожидаемая декларация
- Использование неразрешенной идентифицированный «отмечает конечную точку»
Я искал в течение нескольких часов, как решить эти ошибки на Google, но я не понимаю, что не так с кодом. Если бы кто-то мог направить меня к тому, что нужно решить, было бы очень полезно.
Ошибки - NotesViewController.Swift - Ошибки =
var request = URLRequest(url: notesEndpoint) - Use of unresolved identifier 'notesEndPoint'
LoginViewController.Swift - Ошибки =
self.showAlert(withTitle: "Error", message: error.localizedDescription) - Value of type 'LoginViewController' has no member 'showAlert'
performSegue(withIdentifier: "login", sender: self) - Implicit use of 'self' in closure; use 'self'. to make capture semantics explicit
showAlert(withTitle: "Error", message: error.localizedDescription) - Use of unresolved identifier 'showAlert'
extension UIViewController { -Declaration is only valid at file scope
RegisterViewController.swift -
self.showAlert(withTitle: "Error", message: error.localizedDescription) - Value of type 'RegisterViewController' has no member 'showAlert'
Эти ошибки I» м получение
'нерешенным идентификатор«notesEndpoint'' потому, что вы зафиксируете использовать переменную, которую не заявленную в любом месте. (Где вы создаете «notesEndpoint»?) –
Другие ошибки, вероятно, связаны с отсутствующим скобкой. –
Вы должны указать, какие строки точно дают ошибки, и убедитесь, что каждая из этих строк отмечена полной и точной ошибкой. – rmaddy