斯威夫特 - 我无法解决的错误

时间:2016-09-30 14:00:07

标签: ios swift stormpath

我希望有人可以帮助我解决我在Swift项目中遇到的这些错误。

我对应用程序编码很陌生,所以如果我事先听起来像是一个noob抱歉。

到目前为止,我已经创建了一个带有登录和注册页面的应用程序,它们全部连接在一起。现在我正在做代码部分,将所有这些连接在一起。

我正在使用名为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'

这些是我得到的错误

2 个答案:

答案 0 :(得分:2)

您的openNotes函数缺少括号,这可能是前2个错误的原因。你应该关闭else:

func openNotes(success: Bool, error: NSError?) {
    if let error = error {
        showAlert(withTitle: "Error", message: error.localizedDescription)
    } else {
        performSegue(withIdentifier: "login", sender: self)
    }
}

您的第三个错误"Use of unresolved identifier 'notesEndpoint'"是因为您正在尝试使用尚未在任何位置声明的变量。如果您按照教程进行操作,我猜您错过了这样的一行:

let notesEndpoint = URL(string: "https://stormpathnotes.herokuapp.com/notes")!

答案 1 :(得分:0)

swift3

    let notesEndpoint = "http......."
    let request = URLRequest(url: URL(string: notesEndpoint)!)