如何快速保存响应JSON数组并使用用户默认值进行检索

时间:2018-12-18 06:05:27

标签: json swift alamofire nsuserdefaults swifty-json

我想将kode_pelaksanaan保存为用户默认设置,并使用SwiftyJSON和Alamofire在第二个视图控制器中检索它。 这是我的代码

class ListSelfLearningViewController: UIViewController{

     @IBOutlet weak var collectionView: UICollectionView!

     var listSelfLearning: [ListSelfLearningModel] = [] 

     override func viewDidLoad() {
     super.viewDidLoad()
     fetchData()
   }
}

extension ListSelfLearningViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.listSelfLearning.count
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ListSelfLearningCollectionViewCell", for: indexPath) as! ListSelfLearningCollectionViewCell
    //cell.profileIv.image = listSelfLearning[indexPath.row].listImage
    cell.profileIv.sd_setImage(with: URL(string: listSelfLearning[indexPath.row].listImage))
    cell.title.text = listSelfLearning[indexPath.row].labelName
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize.init(width: UIScreen.main.bounds.width - 20, height: 250)
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let storyboard: UIStoryboard = UIStoryboard(name: "Home", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "ListActivityViewController") as! ListActivityViewController
    navigationController?.pushViewController(vc, animated: true)
}

func fetchData(){
    DispatchQueue.main.async {
        let url = URLs.listImage
        guard let user = helper.getApiUser() else{ return }

        guard let token = helper.getApiToken() else{ return }

        let parameter  = [
            "request": "{\"requestMethod\":\"list_selflearning\",\"user\":\"\(user)\"}"

        ]

        let headers: HTTPHeaders = [
            "Content-Type" : "application/x-www-form-urlencoded",
            "Authorization" : "Bearer \(token)"
        ]

        Alamofire.request(url, method: .post, parameters: parameter, headers: headers).responseJSON(completionHandler: { (response) in
            switch response.result{
            case .success(let value):
                let json = JSON(value)
                if let data = json["responseData"].array{
                    for item in data{
                        let images = item["image_detail"]["path_image"].string
                        let namaPelaksana = item["nama_pelaksanaan"].string

                        if let kode_pelaksanaan = item["kode_pelaksanaan"].string{
                            helper.saveKodePelaksanaan(kode_pelaksanaan: kode_pelaksanaan)
                            print("nilai kode pelaksanaan: \(kode_pelaksanaan)")
                        }

                        let listData = ListSelfLearningModel(listImage: images!, labelName: namaPelaksana!)
                        self.listSelfLearning.append(listData)

                    }
                }

                self.collectionView.reloadData()

            case .failure(let error):
                print(error)
            }
        })
    }
}
}

默认情况下此输出:

nilai kode pelaksanaan: ELR2018120005
nilai kode pelaksanaan: ELR2018120004
nilai kode pelaksanaan: ELR2018120003
nilai kode pelaksanaan: ELR2018120001
nilai kode pelaksanaan: ELR2018050004

但是当我在第二类中检索参数时,却没有像保存在Userdefault中那样得到输出。

这是我在第二个视图控制器中的代码:

import UIKit
import SwiftyJSON
import Alamofire
import SDWebImage

class ListActivityViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!
var listActivity: [ListActivity] = []

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
    // Do any additional setup after loading the view.
    let nibCell = UINib(nibName: "ListActivityTableViewCell", bundle: nil)
    tableView.register(nibCell, forCellReuseIdentifier: "ListActivityTableViewCell")
    fetchData()
}

}

    extension ListActivityViewController: UITableViewDataSource, UITableViewDelegate{
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return listActivity.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ListActivityTableViewCell", for: indexPath) as! ListActivityTableViewCell

    cell.title.text = listActivity[indexPath.row].pathImage
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let segueIdentifier: String
    switch indexPath.section {
    case 0:
        segueIdentifier = "webView"
    case 1:
        segueIdentifier = "ujian"
    default:
        segueIdentifier = ""
    }
    self.performSegue(withIdentifier: segueIdentifier, sender: self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let indexPath = self.tableView.indexPathForSelectedRow

    switch indexPath?.section {
    case 0:
        let vc = segue.destination as! DetailPdfViewController
        let user = listActivity[(indexPath?.row)!]
        vc.webSite = user.pathPdf
    default:
        break
    }
}
func fetchData(){
    DispatchQueue.main.async {
        let url = URLs.listActivity
        guard let user = helper.getApiUser() else{ return }
        guard let token = helper.getApiToken() else{ return }
        guard let kodePelaksanaan = helper.getKodePelaksanaan() else{ return }

        print(kodePelaksanaan)

        let parameter =  [
            "request" : "{\"requestMethod\":\"detail_selflearning\",\"user\":\"\(user)\",\"kode_pelaksanaan\":\"\(kodePelaksanaan)\"}"
        ]

        let headers: HTTPHeaders = [
            "Content-Type" : "application/x-www-form-urlencoded",
            "Authorization" : "Bearer \(token)"
        ]

        Alamofire.request(url, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: headers).responseJSON(completionHandler: { (response) in

            switch response.result{
            case .success(let value):
                let json = JSON(value)

                let data1 = json["responseData"]["data"]["materi_selflearning"]

                for item in data1.array!{

                    if (item["jenis_materi"] == "2" || item["jenis_materi"] == "3" || item["jenis_materi"] == "99"){

                        let image_detail = item["nama_pelaksanaan"].stringValue
                        let pdfDetail = item["path_file"].stringValue
                        let listActivitied = ListActivity(pathImage: image_detail, pathPdf: pdfDetail)

                        self.listActivity.append(listActivitied)
                        self.tableView.reloadData()
                    }

                }

            case .failure(let error):
                print(error)
            }
        })

    }      
    }
    }

这是我在第二个视图控制器中获得的输出:

  nilai kode pelaksanaan: ELR2018050004

我想像这样在第二个视图控制器中获取输出:

  nilai kode pelaksanaan: ELR2018120005
  nilai kode pelaksanaan: ELR2018120004
  nilai kode pelaksanaan: ELR2018120003
  nilai kode pelaksanaan: ELR2018120001
  nilai kode pelaksanaan: ELR2018050004

这是我的班级助手:

  class helper: NSObject {
     class func saveKodePelaksanaan(kode_pelaksanaan: String){
    let def = UserDefaults.standard
    def.set(kode_pelaksanaan, forKey: "kode_pelaksanaan")
    def.synchronize()
   }

  class func getKodePelaksanaan() -> String? {
    let def = UserDefaults.standard
    return def.object(forKey: "kode_pelaksanaan") as? String
    }
  }

2 个答案:

答案 0 :(得分:0)

希望此消息对您有帮助

您试图仅保存一个字符串,如下面的函数所示:-

class func saveKodePelaksanaan(kode_pelaksanaan: String){
let def = UserDefaults.standard
def.set(kode_pelaksanaan, forKey: "kode_pelaksanaan")
def.synchronize()
}

但是它应该在函数参数中包含字典或数组,如下所示

class func saveKodePelaksanaan(kode_pelaksanaan: array){
 let def = UserDefaults.standard
 def.set(kode_pelaksanaan, forKey: "kode_pelaksanaan")
 def.synchronize()
}

//或

class func saveKodePelaksanaan(kode_pelaksanaan: dictionary){
 let def = UserDefaults.standard
 def.set(kode_pelaksanaan, forKey: "kode_pelaksanaan")
 def.synchronize()
}

您还应该在for循环完成时调用辅助程序类函数,而不是在循环执行时自动调用以下方法:-

    func fetchData(){
    DispatchQueue.main.async {
        let url = URLs.listImage
        guard let user = helper.getApiUser() else{ return }

        guard let token = helper.getApiToken() else{ return }

        let parameter  = [
            "request": "{\"requestMethod\":\"list_selflearning\",\"user\":\"\(user)\"}"

        ]

        let headers: HTTPHeaders = [
            "Content-Type" : "application/x-www-form-urlencoded",
            "Authorization" : "Bearer \(token)"
        ]

        Alamofire.request(url, method: .post, parameters: parameter, headers: headers).responseJSON(completionHandler: { (response) in
            switch response.result{
            case .success(let value):
                let json = JSON(value)
                if let data = json["responseData"].array{
                    for item in data{
                        let images = item["image_detail"]["path_image"].string
                        let namaPelaksana = item["nama_pelaksanaan"].string

                        let listData = ListSelfLearningModel(listImage: images!, labelName: namaPelaksana!)
                        self.listSelfLearning.append(listData)

                    }

                    // Changes are made here
                    helper.saveKodePelaksanaan(kode_pelaksanaan: self.listSelfLearning)

                }

                self.collectionView.reloadData()

            case .failure(let error):
                print(error)
            }
        })
    }
}

如果您有任何问题,请与我分享,我会尽快更新。

答案 1 :(得分:0)

您可以使用SwiftyUserDefaults