我的代码如下,我在displayMessage
第一个错误是:
SigninViewController.swift:45:17:使用未解析的标识符'displayMessage'
下一个错误是:
SigninViewController.swift:87:13:“SigninViewController”类型的值没有成员'removeActivityIndicator'
import UIKit
class SigninViewController: UIViewController {
@IBOutlet weak var userNameTextFeild: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loginInButtonTapped(_ sender: Any) {
print("log in button tapped")
//Read values from text field
let userName = userNameTextFeild.text
let userPassword = userPasswordTextField.text
// Check if required fields are not empty
if(userName?.isEmpty)! || (userPassword?.isEmpty)!
{
// Display alert message
print("User name \(String(describing: userName)) or password \(String(describing:userPassword)) is empty")
displayMessage(userMessage:"one of the required feilds is missing")
return
}
// Activity indicator
let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
myActivityIndicator.center = view.center
myActivityIndicator.hidesWhenStopped = false
myActivityIndicator.startAnimating()
view.addSubview(myActivityIndicator)
// URL for login
let myUrl = URL(string: "htps://198.228.12.1")
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "content-type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let postString = ["userName": userName!, "userPassword": userPassword!] as [String:String]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: postString,
options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
displayMessage(userMessage:"something went wrong")
return
}
let task = URLSession.shared.dataTask(with: request) { (data: Data?, responce:
URLResponse?, error: Error?) in
self.removeActivityIndicator(activityIndicator: myActivityIndicator)
if error != nil
{
self.displayMessage(userMessage: "Could not sucessfully perform this request")
print("error=\(String(describing:error))")
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
} catch {
self.remoteActivityIndicator(activityIndicator: myActivityIndicator)
self.displayMessage(userMessage: "Could not sucessfully perform this request")
print(error)
}
}
}
}
答案 0 :(得分:0)
首先,您确实需要将代码分解为函数。这将使调试变得更加容易,因为您将确切地知道哪个函数无法正常运行。
JSON请求应该是一个函数,解析JSON应该是另一个,如果你需要更新应该是另一个的屏幕。
现在您的错误,我没有看到displayMessage
被初始化(或定义)的位置,因此您需要先创建它才能使用它。