1.请求得到json
{
"errorno" : 0,
"data" : {
"avatar" : "",
"alipay" : null,
"credit_card" : null,
"id" : 100070,
"nickname" : "起来了",
"account" : "0.00",
"finished" : 0,
"username" : "",
"email" : "",
"tel" : "17386014224",
"usersig" : ""
},
"message" : "success"
}
//网络请求
let para = ["tel":"17386014224","password":"111111"] as [String : AnyObject]
NetworkTool.postMesa(url: API_LOGIN_URL, parameters: para ) { (value) in
//swiftyJSON 解析
let json = JSON(value ?? "123")
//取出data
let dataDict = json["data"].dictionaryValue
//字典转模型
let user : User = User.init(dict: (dataDict as [String : JSON] ))
print(user.tel!)
//归档之后才能保存(模型要encode) 完成!
let data = NSKeyedArchiver.archivedData(withRootObject: user) as NSData
UserDefaults.standard.set(data, forKey: "user")
//解档 完成!
let dataa = UserDefaults.standard.object(forKey: "user") as! NSData
let userrrr : User = NSKeyedUnarchiver.unarchiveObject(with: dataa as Data ) as! User
print( userrrr)
print(userrrr.tel!)
}
//
// User.swift
// task
//
// Created by 柏超曾 on 2017/9/28.
// Copyright © 2017年 柏超曾. All rights reserved.
//
import SwiftyJSON
import Foundation
class User : NSObject, NSCoding {
var avatar : String?
var alipay : String?
var credit_card : String?
var id : String?
var nickname : String?
var account : String?
var finished : String?
var username : String?
var email : String?
var tel : String?
var usersig : String?
// MARK:- 自定义构造函数 KVC实现字典转模型
init(dict : [String : JSON]) {
super.init()
let rrrr :String = (dict["tel"]?.stringValue)!
print(rrrr)
tel = dict["tel"]?.stringValue as String!
print(tel!)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
struct PropertyKey {
static let id = "id"
static let nickname = "nickname"
static let username = "username"
static let tel = "tel"
}
required init?(coder aDecoder: NSCoder) {
id = aDecoder.decodeObject(forKey: PropertyKey.id) as? String
nickname = aDecoder.decodeObject(forKey: PropertyKey.nickname) as? String
tel = aDecoder.decodeObject(forKey: PropertyKey.tel) as? String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: PropertyKey.id)
aCoder.encode(nickname, forKey: PropertyKey.nickname)
aCoder.encode(tel, forKey: PropertyKey.tel)
}
}