我面临下面提到的错误
错误域= NSCocoaErrorDomain代码= 3840" JSON文本未启动 使用数组或对象和选项来允许未设置片段。" UserInfo = {NSDebugDescription = JSON文本不是以数组或 允许片段未设置的对象和选项。}
我已将我的代码包含在下面,请帮助我
import UIKit
class SigninViewController: UIViewController {
@IBOutlet weak var userNameTextFeild: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
@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 here
print("User name \(String(describing: userName)) or password \(String(describing: userPassword)) is empty")
displayMessage(userMessage: "One of the required fields is missing")
return
}
//Create Activity Indicator
let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
// Position Activity Indicator in the center of the main view
myActivityIndicator.center = view.center
// If needed, you can prevent Acivity Indicator from hiding when stopAnimating() is called
myActivityIndicator.hidesWhenStopped = false
// Start Activity Indicator
myActivityIndicator.startAnimating()
view.addSubview(myActivityIndicator)
//Send HTTP Request to perform Sign in
let myUrl = URL(string: "http://198.162.8.80:50000/login/")
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
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?, response: URLResponse?, error: Error?) in
self.removeActivityIndicator(activityIndicator: myActivityIndicator)
if error != nil {
self.displayMessage(userMessage: "Could not successfully perform this request. Please try again later")
print("error=\(String(describing: error))")
return
}
//Let's convert response sent from a server side code to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
if parseJSON["errorMessageKey"] != nil {
self.displayMessage(userMessage: parseJSON["errorMessage"] as! String)
return
}
DispatchQueue.main.async {
let homePage = self.storyboard?.instantiateViewController(withIdentifier: "dashboardViewController") as! dashboardViewController
let appDelegate = UIApplication.shared.delegate
appDelegate?.window??.rootViewController = homePage
}
} else {
//Display an Alert dialog with a friendly error message
self.displayMessage(userMessage: "Could not successfully perform this request. Please try again later")
}
} catch {
self.removeActivityIndicator(activityIndicator: myActivityIndicator)
// Display an Alert dialog with a friendly error message
self.displayMessage(userMessage: "Could not successfully perform this request. Please try again later")
print(error)
}
}
task.resume()
}
@IBAction func registerNewAccountButtonTapped(_ sender: Any) {
print("Register account button tapped")
let registerViewController = self.storyboard?.instantiateViewController(withIdentifier: "registerViewController") as! registerViewController
self.present(registerViewController, animated: true)
}
func displayMessage(userMessage:String) -> Void {
DispatchQueue.main.async {
let alertController = UIAlertController(title: "Alert", message: userMessage, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
// Code in this block will trigger when OK button tapped.
print("Ok button tapped")
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion:nil)
}
}
func removeActivityIndicator(activityIndicator: UIActivityIndicatorView) {
DispatchQueue.main.async{
activityIndicator.stopAnimating()
activityIndicator.removeFromSuperview()
}
}
}
答案 0 :(得分:0)
如错误所述,JSON不是预期的格式,并且未设置allowFragments。所以你可以在这一行中设置它
@IBAction func backButtonAction(_ sender: Any) {
let nc = revealViewController().rearViewController as? UINavigationController
let frontNVC = (nc?.topViewController as? LeftSideViewController)?.frontNVC
_ = frontNVC?.popViewController(animated: true)
}
这可能无法按预期工作,但您需要发布正在返回的实际JSON。
几个笔记: