Я хочу сохранить 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
}
}