Put a standard string on a label - ios

I'm currently trying to make a label showing different text for each user, to have a standard text before this label but not inside the cell on the .xib file.
What i've done until know is this
import UIKit
class profileViewController: UIViewController {
#IBOutlet var lblUsersname: UILabel!
#IBOutlet var lblUserspoints: UILabel!
#IBOutlet var imgViewUserAvatar: UIImageView!
var profileJson : [String:AnyObject] = [ : ]
var userid = ""
var usersname = ""
var userspoints = ""
var usersavatar = ""
var pointtxt = "Points: "
override func viewDidLoad() {
super.viewDidLoad()
let defaults = NSUserDefaults.standardUserDefaults()
if let usersid = defaults.stringForKey("usersId") {
userid = usersid
fetchDatas()
lblUsersname.text = usersname
lblUserspoints.text = userspoints
}else{
print("Error")
}
if let checkedUrl = NSURL(string: usersavatar) {
downloadImage(checkedUrl)
}
}
func fetchDatas(){
let urlara = NSLocalizedString("profileRequest", comment: "")
let loginRequest = receiveData(data1: "id=\(userid)", url1: NSURL(string: urlara)!)
profileJson = loginRequest.fetchData()
if let locationsArray = profileJson["profile"] as? [[String:AnyObject]] {
for locationDictionary in locationsArray {
if let name = locationDictionary["name"] as? String {
usersname = name
}
if let points = locationDictionary["points"] as? String {
userspoints = points
}
if let avatar = locationDictionary["avatar"] as? String {
usersavatar = avatar
}
}
}
}
So now it's show only the number of the points
And i'm trying to make it show
Points: lblUserpoints
Anyone has any idea?

After some tryings i find it out. changed the line
lblUserspoints.text = userspoints
to this
lblUserpoints.text = String(pointtxt) + userpoints
And i had the desired output which was
Points: 2910

Related

dropdown array becomes empty for few cells after adding cells in tableview and scroll up

Initially when I tap of hierarchy button and parentLocationLevelTwoBtnAction at that time parentLocationNameArr is not empty but after adding few more cells and I scroll up parentLocationNameArr is empty
import UIKit
import DropDown
import ObjectMapper
//Stock Btn Cell Delegate
protocol AddStorageLocationMasterBtnCellDelegate : AnyObject {
func didPressButton(_ tag: Int)
func didPressHierachyButton(_ tag: Int)
func didPressHierachytext(_ tag: Int,sender:String)
func didPressParenttext(_ tag: Int,sender:String, id:String)
func didPressParentTwotext(_ tag: Int,sender:String, id:String)
}
class AddStorageLocationMasterTVCell: UITableViewCell {
#IBOutlet var parentLTextLHeight: NSLayoutConstraint!
#IBOutlet weak var bgView: UIView!
#IBOutlet weak var deleteBtn: UIButton!
#IBOutlet weak var storageLocationNameView: UIView!
#IBOutlet var warnDescriptionbtn: UIButton!
#IBOutlet weak var storageLocationNameTF: UITextField!
#IBOutlet var warnNamebtn: UIButton!
#IBOutlet weak var descriptionView: UIView!
#IBOutlet weak var descriptionTextView: UITextView!
#IBOutlet weak var hierachyView: UIView!
#IBOutlet weak var hierachyTF: UITextField!
#IBOutlet weak var hierachyBtn: UIButton!
#IBOutlet weak var parentLocationView: UIView!
#IBOutlet weak var parentLocationTF: UITextField!
#IBOutlet weak var parentBgView: UIView!
#IBOutlet weak var parentHeightConstant: NSLayoutConstraint!
#IBOutlet weak var parentLocationLevelOneBtn: UIButton!
#IBOutlet weak var parentLocationLevelTwoView: UIView!
#IBOutlet weak var parentLocationLevelTwoTF: UITextField!
#IBOutlet weak var parentLocationTextLabel: UILabel!
#IBOutlet weak var stackView: UIStackView!
#IBOutlet weak var stackViewHeight: NSLayoutConstraint!
#IBOutlet weak var parentLcationLabel: UILabel!
var cellDelegate: AddStorageLocationMasterBtnCellDelegate?
let dropDown = DropDown() //2
var selectedId = 0
var accountID = ""
var storageLocationArr = NSMutableArray()
var storageLocationLevelThreeArr = NSMutableArray()
var serviceVC = ServiceController()
var parentLocationDict = [String]()
var parentLocationId = [String]()
var parentLocationArr = [NSArray]()
var parentLocationNameArr = [String]()
var parentLocationNameIdsArr = [String]()
var parentLocationDetailsDict = NSMutableArray()
var parentLocationNameLevethreeArr = [String]()
var parentLocationNameLevethreeIdsArr = [String]()
var parentLocationDetailsLevethreeDict = NSMutableArray()
var levelValue = 0
var idLevelThree = ""
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.parentBgView.isHidden = true
self.parentHeightConstant.constant = 0
storageLocationNameView.layer.borderColor = UIColor.gray.cgColor
storageLocationNameView.layer.borderWidth = 0.5
storageLocationNameView.layer.cornerRadius = 3
storageLocationNameView.clipsToBounds = true
descriptionView.layer.borderColor = UIColor.gray.cgColor
descriptionView.layer.borderWidth = 0.5
descriptionView.layer.cornerRadius = 3
descriptionView.clipsToBounds = true
hierachyView.layer.borderColor = UIColor.gray.cgColor
hierachyView.layer.borderWidth = 0.5
hierachyView.layer.cornerRadius = 3
hierachyView.clipsToBounds = true
parentLocationView.layer.borderColor = UIColor.gray.cgColor
parentLocationView.layer.borderWidth = 0.5
parentLocationView.layer.cornerRadius = 3
parentLocationView.clipsToBounds = true
parentLocationLevelTwoView.layer.borderColor = UIColor.gray.cgColor
parentLocationLevelTwoView.layer.borderWidth = 0.5
parentLocationLevelTwoView.layer.cornerRadius = 3
parentLocationLevelTwoView.clipsToBounds = true
bgView.backgroundColor = .white
bgView.layer.cornerRadius = 5.0
bgView.layer.shadowColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
bgView.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
bgView.layer.shadowRadius = 6.0
bgView.layer.shadowOpacity = 0.7
hierachyTF.text = "Level 1"
selectedId = 1
}
#IBOutlet var parentButton: UIButton!
// override func setSelected(_ selected: Bool, animated: Bool) {
// super.setSelected(selected, animated: animated)
//
// // Configure the view for the selected state
// }
#IBAction func deleteBtnAction(_ sender: UIButton) {
cellDelegate?.didPressButton(sender.tag)
}
var tagVal=Int()
#IBAction func hierachyBtnAction(_ sender: UIButton) {
let selectedTagHierachy = sender.tag
cellDelegate?.didPressHierachyButton(selectedTagHierachy)
dropDown.dataSource = ["Level 1","Level 2","Level 3"]//4
dropDown.anchorView = sender //5
dropDown.bottomOffset = CGPoint(x: 0, y: sender.frame.size.height) //6
dropDown.show() //7
dropDown.selectionAction = { (index: Int, item: String) in //8
// guard let _ = self else { return }
// sender.setTitle(item, for: .normal) //9
self.selectedId = index
self.hierachyTF.text = item
self.cellDelegate?.didPressHierachytext(selectedTagHierachy, sender: item)
print(self.levelValue)
if index == 0 {
self.parentBgView.isHidden = true
self.parentHeightConstant.constant = 0
}
else if index == 1{
self.levelValue = index+1
self.get_StorageLocationMaster_API_Call(level: index+1, tag: selectedTagHierachy)
self.parentBgView.isHidden = false
self.parentHeightConstant.constant = 120
self.parentLcationLabel.text = "Parent Location L1"
self.parentLocationLevelTwoView.isHidden = true
}
else if index == 2{
self.levelValue = index+1
self.get_StorageLocationMaster_API_Call(level: index+1, tag: selectedTagHierachy)
self.parentBgView.isHidden = false
self.parentHeightConstant.constant = 120
self.parentLcationLabel.text = "Parent Location L2 and L1"
self.parentLocationLevelTwoView.isHidden = false
}
}
}
#IBAction func parentLocationBtnAction(_ sender: UIButton) {
let selectedTagParentLocation = sender.tag
// cellDelegate?.didPressParenttext(<#T##tag: Int##Int#>, sender: sender, id: <#T##String#>)
dropDown.dataSource = parentLocationNameLevethreeArr//4
dropDown.anchorView = sender //5
dropDown.bottomOffset = CGPoint(x: 0, y: sender.frame.size.height) //6
dropDown.show() //7
dropDown.selectionAction = { (index: Int, item: String) in //8
// guard let _ = self else { return }
// sender.setTitle(item, for: .normal) //9
self.parentLocationLevelTwoTF.text = item
self.cellDelegate?.didPressParentTwotext(selectedTagParentLocation, sender: item, id:self.parentLocationNameLevethreeIdsArr[index] )
}
}
#IBAction func parentLocationLevelTwoBtnAction(_ sender: UIButton)
{
let selectedTagParentLocation = sender.tag
dropDown.dataSource = parentLocationNameArr//4
dropDown.anchorView = sender //5
dropDown.bottomOffset = CGPoint(x: 0, y: sender.frame.size.height) //6
dropDown.show() //7
dropDown.selectionAction = { (index: Int, item: String) in //8
// guard let _ = self else { return }
// sender.setTitle(item, for: .normal) //9
// if self?.parentLocationNameLevethreeArr.count ?? 0>0
// {
// self?.parentLocationLevelTwoTF.text = self?.parentLocationNameLevethreeArr[0]
// self?.cellDelegate?.didPressParentTwotext(sender.tag, sender: self?.parentLocationNameLevethreeArr[0] ?? "", id: self?.parentLocationNameLevethreeIdsArr[0] ?? "")
// }
self.parentLocationTF.text = item
self.idLevelThree = self.parentLocationNameIdsArr[index]
self.cellDelegate?.didPressParenttext(selectedTagParentLocation, sender: item, id: self.parentLocationNameIdsArr[index] )
print(self.levelValue)
if self.levelValue==3
{
self.get_StorageLocationByParentLocation_API_Call(level: 2, tag: selectedTagParentLocation)
}
}
}
// MARK: Get Storage Location Master API Call
func get_StorageLocationByParentLocation_API_Call(level:Int,tag:Int) {
let defaults = UserDefaults.standard
accountID = (defaults.string(forKey: "accountId") ?? "")
// let newString = parentLocation.replacingOccurrences(of: " ", with: "%20")
if idLevelThree != ""
{
let urlStr = Constants.BaseUrl + getAllStorageLocationByParentUrl + "\(2)/" + "\(idLevelThree)/" + accountID
serviceVC.requestGETURL(strURL: urlStr, success: {(result) in
let respVo:GetStorageLocationMasterRespVo = Mapper().map(JSON: result as! [String : Any])!
DispatchQueue.main.async { [self] in
let status = respVo.STATUS_CODE
let message = respVo.STATUS_MSG
if status == 200 {
if message == "SUCCESS" {
if respVo.result != nil {
if respVo.result!.count > 0 {
let resultObj:[String:Any]=result as? [String:Any] ?? [String:Any]()
let resultArr:NSMutableArray=resultObj["result"]as? NSMutableArray ?? NSMutableArray()
self.storageLocationLevelThreeArr = NSMutableArray()
self.storageLocationLevelThreeArr = resultArr
self.parentLocationNameLevethreeArr.removeAll()
self.parentLocationNameLevethreeIdsArr.removeAll()
for obj in self.storageLocationLevelThreeArr {
let sDict=obj as? NSDictionary
let isCanEd:Bool = sDict?.value(forKey: "canEdit") as? Bool ?? false
// sDict(sDict?[i] as AnyObject).value(forKey: "canEdit") as? Bool
if isCanEd == true {
let slocName = sDict?.value(forKey: "slocName") as? String ?? ""
let idsStr = sDict?.value(forKey: "_id") as? String ?? ""
self.parentLocationNameLevethreeIdsArr.append(idsStr)
self.parentLocationNameLevethreeArr.append(slocName)
print("level 2 : \(parentLocationNameLevethreeArr)")
}
}
if self.parentLocationNameLevethreeArr.count > 0 {
self.parentLocationLevelTwoTF.text = self.parentLocationNameLevethreeArr[0]
self.cellDelegate?.didPressParentTwotext(tag, sender: self.parentLocationNameLevethreeArr[0], id: self.parentLocationNameLevethreeIdsArr[0])
}
// else{
// self.parentLocationLevelTwoTF.text = ""
// }
self.parentLTextLHeight.constant=0
self.parentLocationTextLabel.isHidden=true
self.parentLocationTextLabel.text=""
}
else {
self.parentLTextLHeight.constant=40
self.parentLocationTextLabel.isHidden=false
self.parentLocationTextLabel.text="No parent storage location is created currently. Pls create a parent storage location before creating the storage location when use creates a storage location without a custom parent storage location"
self.parentLocationTextLabel.numberOfLines = 0
self.parentLocationTextLabel.lineBreakMode = .byWordWrapping
self.parentLocationLevelTwoTF.text = ""
self.parentLocationNameLevethreeArr=[String]()
self.parentLocationNameLevethreeIdsArr=[String]()
}
}
}
}
else {
// self.view.makeToast(message)
}
}
}) { (error) in
// self.view.makeToast("app.SomethingWentToWrongAlert".localize())
print("Oops, your connection seems off... Please try again later")
}
}
else
{
self.parentLTextLHeight.constant=40
self.parentLocationTextLabel.isHidden=false
self.parentLocationTextLabel.text="No level 2 storage location exists currently. Pls create a level 2 storage location before creating levele 3 storage location"
}
}
// MARK: Get AddressBook API Call
func get_StorageLocationMaster_API_Call(level:Int,tag:Int) {
let defaults = UserDefaults.standard
accountID = (defaults.string(forKey: "accountId") ?? "")
let urlStr = Constants.BaseUrl + getAllStorageLocationByHierachyLevelUrl + "\(1)/" + accountID
serviceVC.requestGETURL(strURL: urlStr, success: {(result) in
let respVo:GetStorageLocationMasterRespVo = Mapper().map(JSON: result as! [String : Any])!
DispatchQueue.main.async {
let status = respVo.STATUS_CODE
let message = respVo.STATUS_MSG
if status == 200 {
if message == "SUCCESS" {
if respVo.result != nil {
if respVo.result!.count > 0 {
let resultObj:[String:Any]=result as? [String:Any] ?? [String:Any]()
let resultArr:NSMutableArray=resultObj["result"]as? NSMutableArray ?? NSMutableArray()
print(resultArr)
self.storageLocationArr = NSMutableArray()
self.storageLocationArr = resultArr
if self.storageLocationArr.count==0
{
self.parentLTextLHeight.constant=40
self.parentLocationTextLabel.isHidden=false
}
else
{
self.parentLTextLHeight.constant=0
self.parentLocationTextLabel.isHidden=true
let ddict=self.storageLocationArr[0] as? NSDictionary
self.parentLocationNameArr = [String]()
self.parentLocationNameIdsArr = [String]()
for obj in self.storageLocationArr {
let sDict=obj as? NSDictionary
let isCanEd:Bool = sDict?.value(forKey: "canEdit") as? Bool ?? false
// sDict(sDict?[i] as AnyObject).value(forKey: "canEdit") as? Bool
if isCanEd == true {
let slocName = sDict?.value(forKey: "slocName") as? String ?? ""
let idsStr = sDict?.value(forKey: "_id") as? String ?? ""
self.parentLocationNameIdsArr.append(idsStr)
self.parentLocationNameArr.append(slocName)
print(self.parentLocationNameArr)
self.parentLocationDetailsDict.addObjects(from: sDict?.value(forKey: "parentLocationDetails") as? NSMutableArray as! [Any])
}
}
let parentLocationDetails=ddict?.value(forKey: "parentLocationDetails")as? NSArray
print(self.levelValue)
if self.levelValue==3
{
if self.parentLocationNameArr.count>0
{
self.idLevelThree = self.parentLocationNameIdsArr[0] ?? ""
self.parentLocationTF.text = self.parentLocationNameArr[0]
self.cellDelegate?.didPressParenttext(tag, sender: self.parentLocationNameArr[0], id: self.parentLocationNameIdsArr[0])
}
else{
self.parentLTextLHeight.constant=40
self.parentLocationTextLabel.isHidden=false
self.parentLocationTextLabel.text="No level 2 storage location exists currently. Pls create a level 2 storage location before creating levele 3 storage location"
}
// if self.parentLocationDetailsDict.count > 0
// {
self.get_StorageLocationByParentLocation_API_Call(level: 2, tag:tag)
print("parent level 2 :\(self.parentLocationNameLevethreeArr)")
// }
}
else
{
if self.parentLocationNameArr.count>0
{
self.parentLocationTF.text = self.parentLocationNameArr[0]
self.cellDelegate?.didPressParenttext(tag, sender: self.parentLocationNameArr[0], id: self.parentLocationNameIdsArr[0])
}
else{
self.parentLTextLHeight.constant=40
self.parentLocationTextLabel.isHidden=false
self.parentLocationTextLabel.text="No level 1 storage location exists currently. Pls create a level 1 storage location before creating levele 3 storage location"
}
}
}
}
else {
}
}
}
}
else {
// self.view.makeToast(message)
}
}
}) { (error) in
// self.view.makeToast("app.SomethingWentToWrongAlert".localize())
print("Oops, your connection seems off... Please try again later")
}
}
}
Thanks in advance🙏

how to customizing swift firabase didselectedrowat

hello i am begginer to swift i get an error "Cannot assign value of type 'Character' to type '[String]'" how can i fix that my brain is now lost in this code blog enter code here
import UIKit
import FirebaseFirestore
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
class PhoneViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var phoneModelText = [String]()
var imeiAdressText = [String]()
var userNameText = [String]()
var idText = [String]()
var phoneNumberText = [String]()
var detailsText = [String]()
var dateText = [String]()
var priceText = [String]()
var adressText = [String]()
var selectedPhoneModelText = ""
var selectedimeiAdressText = ""
var selecteduserNameText = ""
var selectedidText = ""
var selectedphoneNumberText = ""
var selecteddetailsText = ""
var selecteddateText = ""
var selectedpriceText = ""
var selectedadressText = ""
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
tableView.dataSource = self
tableView.delegate = self
getdata()
}
func makeAlert(titleInput: String, messageInput : String) {
let alert = UIAlertController(title: titleInput, message: messageInput, preferredStyle: UIAlertController.Style.alert)
let okButton = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
alert.addAction(okButton)
present(alert, animated: true, completion: nil)
}
func fetchBook(documentId: String) {
let db = Firestore.firestore()
let docRef = db.collection("Databases").document(documentId)
docRef.getDocument { document, error in
if let error = error as NSError? {
self.makeAlert(titleInput: "alert", messageInput: "\(error.localizedDescription)")
}
else {
if let document = document {
let id = document.documentID
let data = document.data()
let phonemodel = data?["phoneName"] as? String ?? ""
let imeiadress = data?["imeiNumberText"] as? Int ?? 0
let username = data?["userNameText"] as? String ?? ""
let idcard = data?["idCardtext"] as? Int ?? 0
let phonenumber = data?["phoneNumberText"] as? Int ?? 0
let adress = data?["adressNameText"] as? String ?? ""
let details = data?["detailSectionText"] as? String ?? ""
let date = data?["currentDateText"] as? String ?? ""
let price = data?["priceValueText"] as? Int ?? 0
let image = data?["imageurl"] as? String ?? ""
DispatchQueue.main.async {
self.selectedphoneNumberText = phonemodel
self.phoneModelText.text = phonemodel
self.imeiAdressText.text = String(imeiadress)
self.userNameText.text = username
self.idText.text = String(idcard)
self.phoneNumberText.text = String(phonenumber)
self.adressText.text = adress
self.detailsText.text = details
self.dateText.text = date
self.priceText.text = String(price)
}
}
}
}
}
}
extension PhoneViewController : UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return phoneModelText.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = phoneModelText[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// how i customizing there
performSegue(withIdentifier: "toPhoneListView", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toPhoneListView" {
let destinationVC = segue.destination as! PhoneListViewController
destinationVC.selectedPhoneModelText
destinationVC.selectedimeiAdressText
destinationVC.selecteduserNameText
destinationVC.selectedidText
destinationVC.selectedphoneNumberText
destinationVC.selecteddetailsText
destinationVC.selecteddateText
destinationVC.selectedpriceText
destinationVC.selectedadressText
}
}
}
This is how your phoneModelText is defined
var phoneModelText = [String]()
that indicates that phoneModelText is an array of strings, so it would look something like this
phoneModelText[0] = "Some String"
phoneModelText[1] = "Another string"
but then later you're attempting to assign string to that array
self.phoneModelText.text = phonemodel
And that's not how arrays work. If you want to add phoneModel to the array it would be this
self.phoneModelText.append(phoneModel) //assume phoneModel = "yet another string"
so then the array would look like this
phoneModelText[0] = "Some String"
phoneModelText[1] = "Another string"
phoneModelText[2] = "yet another string"
In general I would suggest naming your vars so they more represent what they contain - instead of phoneModelText, call it phoneModelTextArray. That wil reduce confusion and make the code more readable.
As far as a solution, it's not clear why there are a bunch of arrays
var phoneModelText = [String]()
var imeiAdressText = [String]()
var userNameText = [String]()
but I suggest changing all of that around. One option is to define a class with properties and then have an array of classes
class ContactClass {
var id = ""
var phoneText = ""
var imeiAdressText = ""
var userNameText = ""
}
and then an array of classes within your controller
var contactArray = [ContactClass]()
and then lastly, when reading data from Firebase, instantiate the class, populate the class properties and add the class to the array
else {
if let document = document {
let contact = ContactClass()
contact.id = document.documentID
contact.phoneText = data?["phoneName"] as? String ?? ""
contact.imeiAdressText = data?["imeiNumberText"] as? Int ?? 0
contact.userNameText = data?["userName"] as? String ?? ""
self.contactArray.append(contact)

Parsing json data through alamofire in table view cells

I am trying to parse json data in my table view cell and its not parsing and not showing the cells . I am attaching all my code please tell me whats the mistake i am doing .. I am not getting any error but the cells are not showing. I have made separate class and functions for json parsing and storing it in an array .
//
// ViewController.swift
// WorkingFeed2
//
// Created by keshu rai on 08/08/17.
// Copyright © 2017 keshu rai. All rights reserved.
//
import UIKit
import Alamofire
import MediaPlayer
class ViewController: UIViewController , UITableViewDelegate , UITableViewDataSource{
var post : PostData!
var posts = [PostData]()
typealias DownloadComplete = () -> ()
var arrayOfPostData : [String] = []
#IBOutlet weak var feedTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
feedTable.dataSource = self
feedTable.delegate = self
}
func downloadPostData(completed: #escaping DownloadComplete) {
Alamofire.request("https://new.example.com/api/posts/get_all_posts").responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String,AnyObject> {
if let successcode = dict["STATUS_CODE"] as? Int {
if successcode == 1 {
if let postsArray = dict["posts"] as? [Dictionary<String,AnyObject>]
{
for obj in postsArray
{
let post = PostData(postDict: obj)
self.posts.append(post)
print(obj)
}
// self.posts.remove(at: 0)
self.feedTable.reloadData()
}
}
}
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 419
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : ImageTableViewCell = self.feedTable.dequeueReusableCell(withIdentifier: "contentViewReuse") as! ImageTableViewCell
let post = posts[indexPath.row]
print(post)
cell.configureCell(post : post)
return cell
}
}
This is my PostData Class.
import Foundation
class PostData {
var _profileImageURL : String?
var _fullName : String?
var _location : String?
var _title : String?
var _postTime : String?
var _likes : Int?
var _comments : Int?
var _mediaType : String?
var _contentURL : String?
var _content : String?
var _plocation : String?
var profileImageURL : String
{
if _profileImageURL == nil {
_profileImageURL = ""
}
return _profileImageURL!
}
var fullName : String
{
if _fullName == nil {
_fullName = ""
}
return _fullName!
}
var location : String {
if _location == nil {
_location = ""
}
return _location!
}
var title : String {
if _title == nil {
_title = ""
}
return _title!
}
var postTime : String {
if _postTime == nil {
_postTime = ""
}
return _postTime!
}
var likes : Int {
if _likes == nil {
_likes = 0
}
return _likes!
}
var comments : Int {
if _comments == nil {
_comments = 0
}
return _comments!
}
var mediaType : String {
if _mediaType == nil {
_mediaType = ""
}
return _mediaType!
}
var contentURL : String {
if _contentURL == nil {
_contentURL = ""
}
return _contentURL!
}
var content : String {
if _content == nil {
_content = ""
}
return _content!
}
var pLocation : String {
if _plocation == nil {
_plocation = ""
}
return _plocation!
}
init(postDict : Dictionary<String , AnyObject>)
{
if let postsArray = postDict["posts"] as? [Dictionary<String,AnyObject>]
{
for i in 1..<postsArray.count
{
let fullName1 = postsArray[i]["full_name"] as? String
self._fullName = fullName1
let profileImageURL1 = postsArray[i]["profile_pic"] as? String
self._profileImageURL = profileImageURL1
let location1 = postsArray[i]["user_city"] as? String
self._location = location1
let title1 = postsArray[i]["title"] as? String
self._title = title1
let postTime1 = postsArray[i]["order_by_date"] as? String
self._postTime = postTime1
let likes1 = postsArray[i]["liked_count"] as? Int
self._likes = likes1
let comments1 = postsArray[i]["comment_count"] as? Int
self._comments = comments1
let mediaType1 = postsArray[i]["media_path"] as? String
self._mediaType = mediaType1
let contentURL1 = postsArray[i]["media_path"] as? String
self._contentURL = contentURL1
let content1 = postsArray[i]["content"] as? String
self._content = content1
let plocation1 = postsArray[i]["location"] as? String
self._plocation = plocation1
}
}
}
}
This is my PostDataTableViewCell code.
import UIKit
import Alamofire
class PostDataTableViewCell: UITableViewCell {
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var titlePost: UILabel!
#IBOutlet weak var profileFullName: UILabel!
#IBOutlet weak var profileUserLocation: UILabel!
#IBOutlet weak var likeBtn: UIButton!
var buttonAction: ( () -> Void) = {}
var pressed = false
#IBAction func likeBtnPressed(_ sender: Any) {
if !pressed {
let image = UIImage(named: "Like-1.png") as UIImage!
likeBtn.setImage(image, for: .normal)
pressed = true
} else {
let image = UIImage(named: "liked.png") as UIImage!
likeBtn.transform = CGAffineTransform(scaleX: 0.15, y: 0.15)
UIView.animate(withDuration: 2.0,
delay: 0,
usingSpringWithDamping: 0.2,
initialSpringVelocity: 6.0,
options: .allowUserInteraction,
animations: { [weak self] in
self?.likeBtn.transform = .identity
},
completion: nil)
likeBtn.setImage(image, for: .normal)
pressed = false
}
}
#IBAction func commentBtnPressed(_ sender: Any) {
print("Commented")
}
#IBAction func shareBtnPressed(_ sender: Any) {
self.buttonAction()
}
#IBAction func readContentBtnPressed(_ sender: Any) {
print("Read")
}
#IBOutlet weak var contentPostLabel: UILabel!
#IBOutlet weak var contentTypeView: UIView!
#IBOutlet weak var likeAndCommentView: UIView!
#IBOutlet weak var numberOfLikes: UILabel!
#IBOutlet weak var numberOfComments: UILabel!
#IBOutlet weak var postLocation: UILabel!
#IBOutlet weak var postTimeOutlet: UILabel!
func configureCell(post : PostData)
{
titlePost.text = "\(post.title)"
profileFullName.text = "\(post.fullName)"
profileUserLocation.text = "\(post.location)"
numberOfLikes.text = "\(post.likes) Likes"
numberOfComments.text = "\(post.comments) Comments"
postLocation.text = "\(post.pLocation)"
postTimeOutlet.text = "\(post.postTime)"
let url = URL(string: post.profileImageURL)
let data = try? Data(contentsOf: url!)
profileImage.image = UIImage(data: data!)
contentPostLabel.text = "\(post.content)"
if post.mediaType == "image"
{
let url1 = URL(string: post.contentURL)
let data1 = try? Data(contentsOf: url1!)
let image = UIImage(data: data1!)
let imageToView = UIImageView(image: image!)
imageToView.frame = CGRect(x: 0, y: 0, width: 375 , height: 250)
imageToView.contentMode = UIViewContentMode.scaleToFill
contentTypeView.addSubview(imageToView)
}
else if post.mediaType == "null"
{
print("Status")
}
else if post.mediaType == "video"
{
print("Video")
}
else if post.mediaType == "youtube"
{
print("youtube")
}
}
}
Most likely the issue occurs because you are trying to parse the value for key posts twice, once in PostData and once in ViewController.
First of all in Swift 3 a JSON dictionary is [String:Any], secondly – as already mentioned in my comment – private backing variables are nonsense in Swift.
The class PostData can be reduced to
class PostData {
let profileImageURL : String
let fullName : String
let location : String
let title : String
let postTime : String
let likes : Int
let comments : Int
let mediaType : String
let contentURL : String
let content : String
let plocation : String
init(postDict : [String:Any])
{
fullName = postDict["full_name"] as? String ?? ""
profileImageURL = postDict["profile_pic"] as? String ?? ""
location = postDict["user_city"] as? String ?? ""
title = postDict["title"] as? String ?? ""
postTime = postDict["order_by_date"] as? String ?? ""
likes = postDict["liked_count"] as? Int ?? 0
comments = postDict["comment_count"] as? Int ?? 0
mediaType = postDict["media_path"] as? String ?? ""
contentURL = postDict["media_path"] as? String ?? ""
content = postDict["content"] as? String ?? ""
plocation = postDict["location"] as? String ?? ""
}
}

My local JSON serialization/parsing is not working?

Video showing the problem at runtime: https://www.youtube.com/watch?v=INVTDEJ8ZqY
I am having a lot of trouble correctly parsing the JSON from a local JSON file, storing it into an array and then displaying it in my view.
My app doesn't crash. My 4 buttons and 1 label simply do not change values. They just get those sample values I added in there "Question 1", "Question 2", etc...
How do I get it to display the values from my JSON file ? It looks like this
/* Question label storyboard outlet */
#IBOutlet weak var questionLabel: UILabel!
// Answer button storyboard outlets
#IBOutlet weak var topLeftButton: UIButton!
#IBOutlet weak var topRightButton: UIButton!
#IBOutlet weak var bottomLeftButton: UIButton!
#IBOutlet weak var bottomRightButton: UIButton!
/* Questions Set */
var questionObjects = NSMutableOrderedSet(capacity: 100)
override func viewDidLoad() {
super.viewDidLoad()
getQuestionsFromJSONFile()
displayQuestion(0, jsonObjectsSet: questionObjects)
let string = "some Random Question"
questionLabel.text = string.capitalizeFirstCharacter
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getQuestionsFromJSONFile() {
var questionsJSONData: NSData? = nil
do {
let pathToQuestionsJSONFile = try NSBundle.mainBundle().pathForResource("Trivia_100-199", ofType: "json")
do {
questionsJSONData = try NSData(contentsOfFile: pathToQuestionsJSONFile!, options: NSDataReadingOptions.DataReadingMappedIfSafe)
let questionsJSONContent = JSON(data: questionsJSONData!)
if let object : [String:[String:AnyObject]] = questionsJSONContent.object as? [String:[String:AnyObject]] {
parseJSONContentIntoObjects(object)
}
} catch let error as NSError {
print(error.localizedDescription)
}
/*
if let questionsJSONContent = JSON(data: questionsJSONData!) as? [String: [String : AnyObject]] {
parseJSONContentIntoObjects(questionsJSONContent) // PSE: Potential Source of Error
}
*/
} catch let error as NSError {
print(error.localizedDescription)
print(error.localizedFailureReason)
print(error.localizedRecoveryOptions)
print(error.localizedRecoverySuggestion)
}
}
func parseJSONContentIntoObjects(jsonData: [String: [String : AnyObject]]) {
var questionHasAProperAnswer = false // indicator to determine if a proper answer was provided by the API for this specific question
let jsonObjects = NSMutableOrderedSet(capacity: 100)
for (questionAnswer,questionPropertiesSubJson):(String,[String:AnyObject]) in jsonData {
if let questionObject = Question(questionObjectSubJson: questionPropertiesSubJson) as? Question { // All parsing code is in the model file (Question.swift)
if let answerText = questionObject.questionAnswer as? String {
let questionExclusionKeywords = ["the Earth probably", "boring", "uninteresting", "unremarkable", "we do not know", "nothing", "remarkable", "a number for which", "missing a fact"]
for questionExclusionKeyword in (questionExclusionKeywords as? [String])! {
questionHasAProperAnswer = !answerText.containsString(questionExclusionKeyword)
/*
if questionHasAProperAnswer {
jsonObjects.addObject(questionObject)
}
}
if answerText.containsAny(questionExclusionKeywords) {
jsonObjects.addObject(questionObject)
}
*/
jsonObjects.addObject(questionObject)
}
}
}
questionObjects = jsonObjects
if questionObjects.count == 0 {
let fillerObject = Question(questionText: "Some question", questionAnswer: 1234, questionFalseAnswer1: "333", questionFalseAnswer2: "444", questionFalseAnswer3: "555")
questionObjects.addObject(fillerObject)
}
}
}
func displayQuestion(questionIndex: Int, jsonObjectsSet: NSMutableOrderedSet) {
if let specificQuestionObject = jsonObjectsSet.objectAtIndex(questionIndex) as? Question {
if let questionText = specificQuestionObject.questionText {
questionLabel.text = questionText
}
if let questionAnswer = specificQuestionObject.questionAnswer as? String {
let capitalizedQuestionAnswer = questionAnswer.capitalizeFirstCharacter
topLeftButton.titleLabel?.text = capitalizedQuestionAnswer
}
bottomLeftButton.titleLabel?.text = "Some false answer"
topRightButton.titleLabel?.text = "Some other false answer"
bottomRightButton.titleLabel?.text = "Another random false answer"
}
}
For buttons, you should use setTitle(forState:). For example:
button.setTitle("foo", forState: .Normal)

How do I properly parse the JSON from this local JSON?

I am having a lot of trouble correctly parsing the JSON from a local JSON file, storing it into an array and then displaying it in my view.
My app does not crash. The labels I have on the screen (4 buttons and 1 label) simply do not change values. They just get those sample values I added in there "Question 1", "Question 2", etc...
How do I get it to display the values from my JSON file ? It looks like this
/* Question label storyboard outlet */
#IBOutlet weak var questionLabel: UILabel!
// Answer button storyboard outlets
#IBOutlet weak var topLeftButton: UIButton!
#IBOutlet weak var topRightButton: UIButton!
#IBOutlet weak var bottomLeftButton: UIButton!
#IBOutlet weak var bottomRightButton: UIButton!
/* Questions Set */
var questionObjects = NSMutableOrderedSet(capacity: 100)
override func viewDidLoad() {
super.viewDidLoad()
getQuestionsFromJSONFile()
displayQuestion(0, jsonObjectsSet: questionObjects)
let string = "some Random Question"
questionLabel.text = string.capitalizeFirstCharacter
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getQuestionsFromJSONFile() {
var questionsJSONData: NSData? = nil
do {
let pathToQuestionsJSONFile = try NSBundle.mainBundle().pathForResource("Trivia_100-199", ofType: "json")
do {
questionsJSONData = try NSData(contentsOfFile: pathToQuestionsJSONFile!, options: NSDataReadingOptions.DataReadingMappedIfSafe)
let questionsJSONContent = JSON(data: questionsJSONData!)
if let object : [String:[String:AnyObject]] = questionsJSONContent.object as? [String:[String:AnyObject]] {
parseJSONContentIntoObjects(object)
}
} catch let error as NSError {
print(error.localizedDescription)
}
/*
if let questionsJSONContent = JSON(data: questionsJSONData!) as? [String: [String : AnyObject]] {
parseJSONContentIntoObjects(questionsJSONContent) // PSE: Potential Source of Error
}
*/
} catch let error as NSError {
print(error.localizedDescription)
print(error.localizedFailureReason)
print(error.localizedRecoveryOptions)
print(error.localizedRecoverySuggestion)
}
}
func parseJSONContentIntoObjects(jsonData: [String: [String : AnyObject]]) {
var questionHasAProperAnswer = false // indicator to determine if a proper answer was provided by the API for this specific question
let jsonObjects = NSMutableOrderedSet(capacity: 100)
for (questionAnswer,questionPropertiesSubJson):(String,[String:AnyObject]) in jsonData {
if let questionObject = Question(questionObjectSubJson: questionPropertiesSubJson) as? Question { // All parsing code is in the model file (Question.swift)
if let answerText = questionObject.questionAnswer as? String {
let questionExclusionKeywords = ["the Earth probably", "boring", "uninteresting", "unremarkable", "we do not know", "nothing", "remarkable", "a number for which", "missing a fact"]
for questionExclusionKeyword in (questionExclusionKeywords as? [String])! {
questionHasAProperAnswer = !answerText.containsString(questionExclusionKeyword)
/*
if questionHasAProperAnswer {
jsonObjects.addObject(questionObject)
}
}
if answerText.containsAny(questionExclusionKeywords) {
jsonObjects.addObject(questionObject)
}
*/
jsonObjects.addObject(questionObject)
}
}
}
questionObjects = jsonObjects
if questionObjects.count == 0 {
let fillerObject = Question(questionText: "Some question", questionAnswer: 1234, questionFalseAnswer1: "333", questionFalseAnswer2: "444", questionFalseAnswer3: "555")
questionObjects.addObject(fillerObject)
}
}
}
func displayQuestion(questionIndex: Int, jsonObjectsSet: NSMutableOrderedSet) {
if let specificQuestionObject = jsonObjectsSet.objectAtIndex(questionIndex) as? Question {
if let questionText = specificQuestionObject.questionText {
questionLabel.text = questionText
}
if let questionAnswer = specificQuestionObject.questionAnswer as? String {
let capitalizedQuestionAnswer = questionAnswer.capitalizeFirstCharacter
topLeftButton.titleLabel?.text = capitalizedQuestionAnswer
}
bottomLeftButton.titleLabel?.text = "Some false answer"
topRightButton.titleLabel?.text = "Some other false answer"
bottomRightButton.titleLabel?.text = "Another random false answer"
}
}

Resources