我是一名新的 iOS 开发新手,仍在从 YouTube 学习或阅读一些有关 swift 的电子书等。
实际上,我正在关注 YouTube 上的本教程iOS 登录和注册屏幕教程,了解如何使用 JSON 数据创建 iOS 登录和注册,但我认为该代码在带有 Xcode 8 的 swift 3 中效果不佳。我有一些问题/错误,我现在无法解决问题,我已经用谷歌搜索过了,但我不知道如何解决这个问题。
这是我的 LoginVC.swift 文件中的屏幕截图
这是 LoginVC.swift 中的所有代码
import UIKit
class LoginVC: UIViewController {
@IBOutlet weak var txtUsername: UITextField!
@IBOutlet weak var txtPassword: 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 btnLoginTapped(_ sender: UIButton) {
// let userName = txtUsername.text;
// let userPassword = txtPassword.text;
let username = txtUsername.text
let password = txtPassword.text
if ( username!.isEqual("") || password!.isEqual("") ) {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Please enter Username and Password"
alertView.delegate = self
alertView.addButton(withTitle: "OK")
alertView.show()
} else {
var post:NSString = "username=\(username)&password=\(password)" as NSString
NSLog("PostData: %@",post);
var url:NSURL = NSURL(string:"http://192.168.1.17/userAPI/api/users")!
var postData:NSData = post.data(using: String.Encoding.ascii.rawValue)! as NSData
var postLength:NSString = String( postData.length ) as NSString
var request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.httpBody = postData as Data
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: URLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &reponseError)
if ( urlData != nil ) {
let res = response as! HTTPURLResponse!;
// let dict: [String: Any] = ["key": value]
NSLog("Response code: %ld", res?.statusCode ?? <#default value#>);
if ((res?.statusCode)! >= 200 && (res?.statusCode)! < 300) {
var responseData:NSString = NSString(data:urlData! as Data, encoding:String.Encoding.utf8.rawValue)!
NSLog("Response ==> %@", responseData);
var error: NSError?
let jsonData:NSDictionary = JSONSerialization.jsonObject(with: urlData!, options: JSONSerialization.ReadingOptions.mutableContainers, error: &error) as! NSDictionary
// let jsonData:NSDictionary = JSONSerialization.JSONObjectWithData(urlData!, options:JSONSerialization.ReadingOptions.MutableContainers , error: &error) as! NSDictionary
let success:NSInteger = jsonData.value(forKey: "success") as! NSInteger
//[jsonData[@"success"] integerValue];
NSLog("Success: %ld", success);
if(success == 1) {
NSLog("Login SUCCESS");
var prefs:UserDefaults = UserDefaults.standard
prefs.set(username, forKey: "USERNAME")
prefs.set(1, forKey: "ISLOGGEDIN")
prefs.synchronize()
self.dismiss(animated: true, completion: nil)
} else {
var error_msg:NSString
if jsonData["error_message"] as? NSString != nil {
error_msg = jsonData["error_message"] as! NSString
} else {
error_msg = "Unknown Error"
}
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = error_msg as String
alertView.delegate = self
alertView.addButton(withTitle: "OK")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButton(withTitle: "OK")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failure"
if let error = reponseError {
alertView.message = (error.localizedDescription)
}
alertView.delegate = self
alertView.addButton(withTitle: "OK")
alertView.show()
}
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool
{ //delegate method
textField.resignFirstResponder()
return true
}
}
错误实际上在这些行上:
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &reponseError)
NSLog("Response code: %ld", res?.statusCode ?? <#default value#>);
let jsonData:NSDictionary = JSONSerialization.jsonObject(with: urlData!, options: JSONSerialization.ReadingOptions.mutableContainers, error: &error) as! NSDictionary
我有点卡住了,很困惑如何解决这个问题。
有人可以帮忙解决这个问题吗?我真的很感激。或者有人可以告诉我如何使用 Swift3 中的 API 学习和创建登录屏幕?
这是因为我们在获取数据时没有处理错误。因此我们需要安全地输入种姓数据,然后将其传递给 JsonSerializer。这是代码。
do {
let data = try NSData.init(contentsOfFile: path) as Data
let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
print(jsonArray)
} catch {
}