簡體   English   中英

如何快速保存響應JSON數組並使用用戶默認值進行檢索

[英]How to save response JSON array and retrieve using user default in swift

我想將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
    }
  }

希望此消息對您有幫助

您正在嘗試僅保存一個字符串,如下面的函數所示:-

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)
            }
        })
    }
}

如果您有任何問題,請與我分享,我會盡快更新。

您可以使用SwiftyUserDefaults

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM