如何在Swift 3 whit Alamofire中获取NSDictionary的值? 我想在NSDictionary中使用像json这样的值,并将它们保存为默认值,然后在TableView中查看所有内容
PHP代码
public function getProdottiByUsername($username)
{
$stmt = $this->conn->prepare("SELECT username, id_prodotto, nome_prodotto, categoria, quantita FROM listaprodotti WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$i=0;
$prodotti = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$prodotti[$i]['username'] = $row['username'];
$prodotti[$i]['id_prodotto'] = $row['id_prodotto'];
$prodotti[$i]['nome_prodotto'] = $row['nome_prodotto'];
$prodotti[$i]['categoria'] = $row['categoria'];
$prodotti[$i]['quantita'] = $row['quantita'];
$i++;
}
return $prodotti;
}
}
这就是我得到的东西
{"error":false,"user":{"id":3,"username":"anto","email":"a@a","nome":"Anto","cognome":"xxx","telefono":"1234567892"},"prodotti":[{"username":"anto","id_prodotto":57,"nome_prodotto":"milk","categoria":"milk","quantita":"2"},{"username":"anto","id_prodotto":58,"nome_prodotto":"farina","categoria":"alimento","quantita":"2"}]}
SWIFT CODE
import Alamofire
import UIKit
import AVFoundation
class LoginController1: UIViewController {
//The login script url make sure to write the ip instead of localhost
//you can get the ip using ifconfig command in terminal
let URL_USER_LOGIN = "http://........login.php"
//the defaultvalues to store user data
let defaultValues = UserDefaults.standard
//the connected views
//don't copy instead connect the views using assistant editor
@IBOutlet weak var labelMessage: UILabel!
@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
//the button action function
@IBAction func buttonLogin(_ sender: UIButton) {
//getting the username and password
let parameters: Parameters=[
"username":username.text!,
"password":password.text!
]
//making a post request
Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON
{
response in
//printing response
print(response)
//getting the json value from the server
if let result = response.result.value {
let jsonData = result as! NSDictionary
//if there is no error
if(!(jsonData.value(forKey: "error") as! Bool)){
//getting the user from response
let user = jsonData.value(forKey: "user") as! NSDictionary
//getting user values
let userId = user.value(forKey: "id") as! Int
let userName = user.value(forKey: "username") as! String
let userEmail = user.value(forKey: "email") as! String
let userNome = user.value(forKey: "nome") as! String
let userCognome = user.value(forKey: "cognome") as! String
let userTelefono = user.value(forKey: "telefono") as! String
//saving user values to defaults
self.defaultValues.set(userId, forKey: "userid")
self.defaultValues.set(userName, forKey: "username")
self.defaultValues.set(userEmail, forKey: "useremail")
self.defaultValues.set(userNome, forKey: "usernome")
self.defaultValues.set(userCognome, forKey: "usercognome")
self.defaultValues.set(userTelefono, forKey: "usertelefono")
///prende i valori dei prodotti dalla cella legata a quel username
let row = jsonData.value(forKey: "row") as! NSDictionary
let rowNome_prodotto = prodotti.value(forKey: "nome_prodotto") as! String
let rowCategoria = prodotti.value(forKey: "categoria") as! String
let rowQuantita = prodotti.value(forKey: "quantita") as! String
//saving i valori di questo username
self.defaultValues.set(prodottiNome_prodotto, forKey: "nome_prodotto")
self.defaultValues.set(prodottiCategoria, forKey: "categoria")
self.defaultValues.set(prodottiQuantita, forKey: "quantita")
//Go to the HomeViewController if the login is sucessful
let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
self.navigationController?.pushViewController(ProfiloController, animated: true)
self.dismiss(animated: false, completion: nil)
}else{
//error message in case of invalid credential
let alertController = UIAlertController(title: "Error", message: "Username e password sbagliati", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
if defaultValues.string(forKey: "username") != nil{
let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
self.navigationController?.pushViewController(ProfiloController, animated: true)
}
}
var player: AVPlayer?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let tap = UITapGestureRecognizer(target: self, action: #selector(LoginController1.dismissKeyboard))
view.addGestureRecognizer(tap)
let path = Bundle.main.path(forResource: "introoiphone 7 plus", ofType: "mp4")
player = AVPlayer(url: URL(fileURLWithPath: path!))
player!.actionAtItemEnd = AVPlayerActionAtItemEnd.none;
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.frame
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.view.layer.insertSublayer(playerLayer, at: 0)
NotificationCenter.default.addObserver(self, selector: #selector(LoginController1.playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player!.currentItem)
player!.seek(to: kCMTimeZero)
player!.play()
}
func playerItemDidReachEnd() {
player!.seek(to: kCMTimeZero)
}
func dismissKeyboard(tap: UITapGestureRecognizer) {
print("Keyboard Dismiss Again")
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:1)
您需要将字符串转换为JSON,然后获取值。以下是获取用户级别信息的示例。不要忘记处理展开:)
let str = "{\"error\":false,\"user\":{\"id\":3,\"username\":\"anto\",\"email\":\"a@a\",\"nome\":\"Anto\",\"cognome\":\"xxx\",\"telefono\":\"1234567892\"},\"prodotti\":[{\"username\":\"anto\",\"id_prodotto\":57,\"nome_prodotto\":\"milk\",\"categoria\":\"milk\",\"quantita\":\"2\"},{\"username\":\"anto\",\"id_prodotto\":58,\"nome_prodotto\":\"farina\",\"categoria\":\"alimento\",\"quantita\":\"2\"}]}"
let data = str.data(using: .utf8)
do{
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]
let userDic = json?["user"] as? [String: Any]
dump(userDic?["id"])
dump(userDic?["username"])
}catch let error{
}