I have stored a data as below:-
viewmodel:-
typealias dummyDataSource1 = QM_RestaurtantDataSourceModel
extension dummyDataSource1{
func getJsonDataStored1() ->Array<Dictionary<String,String>>{
let jsonArray = [["name":"Anjapar","imageurl":"https://www.planwallpaper.com/static/images/9-credit-1.jpg","city":"Musheireb,Qatar"],["name":"Aryaas","imageurl":"https://www.planwallpaper.com/static/images/9-credit-1.jpg","city":"Al Muntazah,Qatar"],["name":"India Coffee","imageurl":"","city":"Doha,Qatar"],["name":"Saravana","imageurl":"https://www.planwallpaper.com/static/images/9-credit-1.jpg","city":"Al Muntazah,Qatar"],["name":"Tea Time","imageurl":"","city":"Old Airport,Qatar"]] as Array<Dictionary<String,String>>
return jsonArray
}
i need to display the imageurl:-image in UIImgeView .How to do
i tried with code:-
#IBOutlet weak var name: UILabel!
#IBOutlet weak var city: UILabel!
#IBOutlet weak var imageurl: UILabel!
#IBOutlet weak var images: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setRestaurtantData(restaurtant:QM_RestaurtantModel)
{
self.name.text = restaurtant.name
self.city.text = restaurtant.city
self.imageurl.text = restaurtant.imageurl
}
my model:-
var name :String!
var city :String!
var imageurl :String!
init?(dictionary :JSONDictionary) {
guard let name = dictionary["name"] as? String,
let imageurl = dictionary["imageurl"] as? String,
let city = dictionary["city"] as? String else {
return
}
self.name = name
self.city = city
self.imageurl = imageurl
}
i getting the value as string ,but i need to display the image
Related
I want to move some code from my cell for row into its own cell class to make it a little tidier.
Here is my code.
My array of dictionaries.
var appInfo = [[String:Any]]()
My cell class.
class resultsCell: UITableViewCell {
#IBOutlet weak var iconPicture: UIImageView!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var priceLabel: UILabel!
#IBOutlet weak var ratingLabel: UILabel!
func setInfo() {
}
}
My VC cellForRow.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "resultsCell", for: indexPath) as? resultsCell {
let appCell = appInfo[indexPath.row]
let imageUrl = appCell["artwork"] as? String
if imageUrl == nil {
cell.iconPicture.image = #imageLiteral(resourceName: "NoAlbumImage")
}else {
cell.iconPicture.sd_setImage(with: URL(string: "\(imageUrl!)"))
}
cell.titleLabel.text = appCell["name"] as? String
cell.descriptionLabel.text = appCell["desc"] as? String
cell.priceLabel.text = appCell["price"] as? String
let rating = appCell["rating"]
if rating != nil {
cell.ratingLabel.text = "Rating: \((rating!))"
}
return cell
}else {
return UITableViewCell()
}
}
I want to move my cell.label.text's from the VC to the set info function in the cell class.
Here is my JSON decoding and structs.
import Foundation
var appInfo = [[String:Any]]()
class searchFunction {
static let instance = searchFunction()
func getAppData(completion: #escaping (_ finished: Bool) -> ()) {
guard let url = URL(string: BASE_ADDRESS) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
let appData = try decoder.decode(Root.self, from: data)
appInfo = []
for app in appData.results {
let name = app.trackName
let desc = app.description
guard let rating = app.averageUserRating else { continue }
let price = app.formattedPrice
let artwork = app.artworkUrl60.absoluteString
let appInd = ["name":name, "desc":desc, "rating":rating, "price":price, "artwork":artwork] as [String : Any]
appInfo.append(appInd)
}
completion(true)
}catch let jsonErr {
print("Error seroalizing json", jsonErr)
}
}.resume()
}
}
Structs..
import Foundation
struct Root: Decodable {
var results: [resultsFull]
}
struct resultsFull: Decodable {
var trackName: String
var description: String
var formattedPrice: String
var averageUserRating: Double?
var artworkUrl60: URL
}
First, I would replace that array of dictionaries with an array of structs; that way you don't need all of that downcasting:
struct AppInfo {
var artwork: String?
var title: String?
var description: String?
var price: String?
var rating: String?
}
var appInfo = [AppInfo]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "resultsCell", for: indexPath) as! ResultsCell
cell.appInfo = self.appInfo[indexPath.row]
return cell
}
Then you can use didSet to update your cell with the values from the struct
class ResultsCell:UITableViewCell {
#IBOutlet weak var iconPicture: UIImageView!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var priceLabel: UILabel!
#IBOutlet weak var ratingLabel: UILabel!
var appInfo: AppInfo {
didSet {
iconPicture.image = #imageLiteral(resourceName: "NoAlbumImage")
if let artwork = appInfo.artwork, let artworkURL = URL(string: artwork) {
iconPicture.sd_setImage(with: artworkURL)
}
titleLabel.text = appInfo.title ?? ""
descriptionLabel.text = appInfo.description ?? ""
priceLabel.text = appInfo.price ?? ""
if let rating = appInfo.rating {
ratingLabel.text = "Rating: \(rating)")
} else {
ratingLabel.text = ""
}
}
}
}
Write below function in resultsCell cell.
func setInfo(appCell: [String : Any]) {
let imageUrl = appCell["artwork"] as? String
if imageUrl == nil {
iconPicture.image = #imageLiteral(resourceName: "NoAlbumImage")
}else {
iconPicture.sd_setImage(with: URL(string: "\(imageUrl!)"))
}
titleLabel.text = appCell["name"] as? String
descriptionLabel.text = appCell["desc"] as? String
priceLabel.text = appCell["price"] as? String
let rating = appCell["rating"]
if rating != nil {
ratingLabel.text = "Rating: \((rating!))"
}
}
Now pass your array value to as like below in cellForRowAt method.
let appCell = appInfo[indexPath.row]
cell.setInfo(appCell: appCell)
class ResultsCell: UITableViewCell {
#IBOutlet weak var iconPicture: UIImageView!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var priceLabel: UILabel!
#IBOutlet weak var ratingLabel: UILabel!
func setInfo(_ appCell: [String:Any], inIndexPath: IndexPath, _ cntrl: UIViewController) {
let imageUrl = appCell["artwork"] as? String
if imageUrl == nil {
iconPicture.image = #imageLiteral(resourceName: "NoAlbumImage")
}else {
iconPicture.sd_setImage(with: URL(string: "\(imageUrl!)"))
}
titleLabel.text = appCell["name"] as? String
descriptionLabel.text = appCell["desc"] as? String
priceLabel.text = appCell["price"] as? String
let rating = appCell["rating"]
if rating != nil {
ratingLabel.text = "Rating: \((rating!))"
}
}
}
and in your tableView's delegate write :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(
withIdentifier: "your Results Cell ID from storyboard",
for: indexPath) as? resultsCell {
let appCell = appInfo[indexPath.row]
cell.setInfo(appCell, inIndexPath: indexPath, self)
return cell
}else {
return UITableViewCell()
}
}
For further just remove the array of dictionaries and it's better to use structs of models.
Is being a few weeks and I'm still stuck with this problem here. I'm having a mind block with Api. I'm quite new on this and I really need help.
I have those lines done. The single task is: Get data from my API and post it in my label. I've 4 files/classes being used.
UserProfile
import Foundation
import SwiftyJSON
class UserProfileWork: NSObject {
var workHistoryId = String()
var jobSeekerId = String()
var jobPosition = String()
var employer = String()
var workHistoryName = String()
var responsabilities = String()
var reasonForLeaving = String()
var currentPosition = Int()
var startMonth = String()
var startYear = String()
var endMonth = String()
var endYear = String()
init?(workDict: [String: JSON]){
guard let workHistoryId = workDict["work_history_id"]?.string,
let jobSeekerId = workDict["job_seeker_id"]?.string,
let jobPosition = workDict["position"]?.string,
let employer = workDict["employer"]?.string,
let workHistoryName = workDict["work_history_name"]?.string,
let responsabilities = workDict["responsibilities"]?.string,
let reasonForLeaving = workDict["reason_for_leaving"]?.string,
let currentPosition = workDict["is_current_position"]?.toInt,
let startMonth = workDict["start_month"]?.string,
let startYear = workDict["start_year"]?.string,
let endMonth = workDict["end_month"]?.string,
let endYear = workDict["end_year"]?.string else { return nil}
self.workHistoryId = workHistoryId
self.jobSeekerId = jobSeekerId
self.jobPosition = jobPosition
self.employer = employer
self.workHistoryName = workHistoryName
self.responsabilities = responsabilities
self.reasonForLeaving = reasonForLeaving
self.currentPosition = currentPosition
self.startMonth = startMonth
self.startYear = startYear
self.endMonth = endMonth
self.endYear = endYear
}
}
Api + Userprofile
import Foundation
import Alamofire
import SwiftyJSON
extension API {
class func userProfile(completion: #escaping(_ error: Error?, _ userProfile: [UserProfile]?) ->Void) {
let url = URLs.jobSeekerTest90
guard let api_token = helper.getApiToken() else {
completion(nil, nil)
return
}
let headers: HTTPHeaders = [
"Authorization": "Bearer \(api_token)",
"Accept": "application/json"
]
let parameters = [
"api_token": api_token
]
Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.responseJSON{ response in
switch response.result{
case .failure(let error):
completion(error, nil)
print(error)
case .success(let value):
let json = JSON(value)
print(json)
guard let dataDict = json["data"]["jobSeeker"].array else{
completion(nil, nil)
return
}
var userProfile = [UserProfile]()
for data in dataDict {
if let data = data.dictionary, let profileData = UserProfile.init(dict: data){
userProfile.append(profileData)
}
completion(nil, userProfile)
}
}
}
}
}
And my view Controller ( I had tableview before but I decided to use only scrollView + labeles because I just need to display those single data)
import UIKit
import Alamofire
class ProfileViewController: UIViewController{
#IBOutlet weak var leadingConstraint: NSLayoutConstraint!
#IBOutlet weak var menuView: UIView!
#IBOutlet weak var menuProfilePicture: UIImageView!
#IBOutlet weak var myAccountImageMenu: UIImageView!
#IBOutlet weak var switchProfileImageMenu: UIImageView!
#IBOutlet weak var signOutImageMenu: UIImageView!
//User profile
#IBOutlet weak var userProfilePicture: UIImageView!
#IBOutlet weak var userNameLabel: UILabel!
#IBOutlet weak var userNameJobPositionLabel: UILabel!
//quick facts
#IBOutlet weak var quickFactsLabel: UILabel!
#IBOutlet weak var userLocationImage: UIImageView!
#IBOutlet weak var userLocationLabel: UILabel!
#IBOutlet weak var userWorkExpImage: UIImageView!
#IBOutlet weak var userWorkExpLabel: UILabel!
#IBOutlet weak var educationImage: UIImageView!
#IBOutlet weak var educationLabel: UILabel!
#IBOutlet weak var infoImage: UIImageView!
#IBOutlet weak var infoAboutLabel: UILabel!
// most recent jobs
#IBOutlet weak var recentJobTitleLabel: UILabel!
#IBOutlet weak var userJobTitleLabel: UILabel!
#IBOutlet weak var companyNameLabel: UILabel!
#IBOutlet weak var startFinishLabel: UILabel!
//Education
#IBOutlet weak var highestEducLabel: UILabel!
#IBOutlet weak var programNameLabel: UILabel!
#IBOutlet weak var schoolNameLabel: UILabel!
#IBOutlet weak var startFinishEducLabel: UILabel!
var iconArray: [String]!
var userProfileData : [UserProfile] = []
var userProfileEducation : [UserProfileEducation] = []
var userProfileWork : [UserProfileWork] = []
var menuShowing = false
override func viewDidLoad() {
super.viewDidLoad()
iconArray = ["currentLocationIcon", "dataIcon", "educationIcon", "infiIcon"]
leadingConstraint.constant = -520
menuView.layer.shadowOpacity = 1
menuView.layer.shadowRadius = 5
menuProfilePicture.layer.cornerRadius = 35
menuProfilePicture.clipsToBounds = true
userProfilePicture.layer.cornerRadius = 55
userProfilePicture.clipsToBounds = true
handleRefresh()
userData()
}
private func userData(){
self.userNameLabel.text = ""
self.userNameJobPositionLabel.text = "Job Title"
self.userLocationLabel.text = "User Location"
self.userWorkExpLabel.text = "Work Experience"
self.educationLabel.text = "Education"
self.infoAboutLabel.text = "About me. More about me"
self.userJobTitleLabel.text = "Job title again"
self.companyNameLabel.text = "Company Name"
self.startFinishLabel.text = "12 sep 2010 - 11 sep 2017"
self.programNameLabel.text = "web and mobile app dev"
self.schoolNameLabel.text = "school name"
self.startFinishEducLabel.text = "finished at"
}
//reusable cells
private func handleRefresh(){
API.userProfile { (error: Error?, userProfileData: [UserProfile]?) in
if let userProfileData = userProfileData {
self.userProfileData = userProfileData
}
}
API.userEducation { (error: Error?, userEducation : [UserProfileEducation]?) in
if let userEducation = userEducation {
self.userProfileEducation = userEducation
}
}
API.userWork { (error: Error?, userWork: [UserProfileWork]?) in
if let userWork = userWork {
self.userProfileWork = userWork
}
}
}
//Scroll hidden menu
#IBAction func scrollMenu(_ sender: Any) {
if(menuShowing){
leadingConstraint.constant = -520
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
})
}else{
leadingConstraint.constant = 0
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
})
}
menuShowing = !menuShowing
}
override func dismissKeyboard() {
view.endEditing(true)
}
}
I really need help on this guys. Please, help me!
I made some changes and It worked.
import UIKit
import SwiftyJSON
class UserProfile: NSObject{
var userID = String()
var JobSeekerId = String()
var userFstName = String()
var userLstName = String()
var userFullName = String()
var userJobTitle = String()
var userAbout = String()
var userLocation = String()
var userRecentSalary = String()
var userSalaryHiExpect = String()
var userSalaryLoExpect = String()
var userWebsiteUrl = String()
var userEmail = String()
var userMobile = String()
init?(dict: [String: Any]){
guard let userID = dict["user_id"] as? String,
let jobSeekerId = dict["job_seeker_id"] as? String,
let userFstName = dict["first_name"] as? String,
let userLstName = dict["last_name"] as? String,
let userFullName = dict["job_seeker_name"] as? String,
let userJobTitle = dict["personal_job_title"] as? String,
let userAbout = dict["about"] as? String,
let userLocation = dict["seekingLocations"] as? String,
let userRecentSalary = dict["most_recent_salary"] as? String,
let userSalaryHiExpect = dict["salary_expectation_high"] as? String,
let userSalaryLoExpect = dict["salary_expectation_low"] as? String,
let userWebsiteUrl = dict["website_url"] as? String,
let userEmail = dict["contact_email"] as? String,
let userMobile = dict["contact_mobile"] as? String else { return nil }
self.userID = userID
self.JobSeekerId = jobSeekerId
self.userFstName = userFstName
self.userLstName = userLstName
self.userFullName = userFullName
self.userJobTitle = userJobTitle
self.userAbout = userAbout
self.userLocation = userLocation
self.userRecentSalary = userRecentSalary
self.userSalaryHiExpect = userSalaryHiExpect
self.userSalaryLoExpect = userSalaryLoExpect
self.userWebsiteUrl = userWebsiteUrl
self.userEmail = userEmail
self.userMobile = userMobile
}
}
API+userProfile
import Foundation
import Alamofire
import SwiftyJSON
extension API {
class func userProfile(completion: #escaping(_ error: Error?, _ userProfile: UserProfile?) ->Void) {
let url = URLs.jobSeekerTest90
guard let api_token = helper.getApiToken() else {
completion(nil, nil)
return
}
let headers: HTTPHeaders = [
"Authorization": "Bearer \(api_token)",
"Accept": "application/json"
]
let parameters = [
"api_token": api_token
]
Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.responseJSON{ response in
switch response.result{
case .failure(let error):
completion(error, nil)
print(error)
case .success(let value):
let json = JSON(value)
print(json)
guard let dataDict = json["data"]["jobSeeker"].dictionaryObject else{
completion(nil, nil)
return
}
var userProfile = UserProfile(dict: dataDict)
completion(nil, userProfile)
}
}
}
}
ViewController
import UIKit
import Alamofire
class ProfileViewController: UIViewController{
#IBOutlet weak var leadingConstraint: NSLayoutConstraint!
#IBOutlet weak var menuView: UIView!
#IBOutlet weak var menuProfilePicture: UIImageView!
#IBOutlet weak var menuProfileName: UILabel!
#IBOutlet weak var myProfileJobTitle: UILabel!
#IBOutlet weak var myAccountImageMenu: UIImageView!
#IBOutlet weak var switchProfileImageMenu: UIImageView!
#IBOutlet weak var signOutImageMenu: UIImageView!
//User profile
#IBOutlet weak var userProfilePicture: UIImageView!
#IBOutlet weak var userNameLabel: UILabel!
#IBOutlet weak var userNameJobPositionLabel: UILabel!
//quick facts
#IBOutlet weak var quickFactsLabel: UILabel!
#IBOutlet weak var userLocationImage: UIImageView!
#IBOutlet weak var userLocationLabel: UILabel!
#IBOutlet weak var userWorkExpImage: UIImageView!
#IBOutlet weak var userWorkExpLabel: UILabel!
#IBOutlet weak var educationImage: UIImageView!
#IBOutlet weak var educationLabel: UILabel!
#IBOutlet weak var infoImage: UIImageView!
#IBOutlet weak var infoAboutLabel: UILabel!
// most recent jobs
#IBOutlet weak var recentJobTitleLabel: UILabel!
#IBOutlet weak var userJobTitleLabel: UILabel!
#IBOutlet weak var companyNameLabel: UILabel!
#IBOutlet weak var startFinishLabel: UILabel!
//Education
#IBOutlet weak var highestEducLabel: UILabel!
#IBOutlet weak var programNameLabel: UILabel!
#IBOutlet weak var schoolNameLabel: UILabel!
#IBOutlet weak var startFinishEducLabel: UILabel!
var iconArray: [String]!
var userProfileData : [UserProfile] = []
var userProfileEducation : [UserProfileEducation] = []
var userProfileWork : [UserProfileWork] = []
var menuShowing = false
override func viewDidLoad() {
super.viewDidLoad()
iconArray = ["currentLocationIcon", "dataIcon", "educationIcon", "infiIcon"]
leadingConstraint.constant = -520
menuView.layer.shadowOpacity = 1
menuView.layer.shadowRadius = 5
menuProfilePicture.layer.cornerRadius = 35
menuProfilePicture.clipsToBounds = true
userProfilePicture.layer.cornerRadius = 55
userProfilePicture.clipsToBounds = true
userData()
userWorkProfileData()
userEducationProfileData()
}
private func userData(){
API.userProfile { (error: Error?, userProfileData: UserProfile?) in
if let userProfileData = userProfileData {
self.myProfileJobTitle.text = userProfileData.userFullName
self.menuProfileName.text = userProfileData.userJobTitle
self.userNameLabel.text = userProfileData.userFullName
self.userNameJobPositionLabel.text = userProfileData.userJobTitle
self.userLocationLabel.text = userProfileData.userLocation
self.infoAboutLabel.text = userProfileData.userAbout
self.userJobTitleLabel.text = userProfileData.userJobTitle
}
}
}
//Scroll hidden menu
#IBAction func scrollMenu(_ sender: Any) {
if(menuShowing){
leadingConstraint.constant = -520
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
})
}else{
leadingConstraint.constant = 0
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
})
}
menuShowing = !menuShowing
}
override func dismissKeyboard() {
view.endEditing(true)
}
}
How can i passing data uiviewController from uiview
I am Using function but it was not working
protocol name is startcalldelegate and function name is startcall
UIView Code
protocol StartCallDelegate: class {
func startCall(localNickname :String, remoteNickname :String)}
class CardView: UIView {
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
weak var delegate: CardViewDelegate?
weak var socketdelegate: StartCallDelegate?
#IBOutlet weak var UserPhoto: UIImageView!
#IBOutlet weak var UserNickName: UILabel!
#IBOutlet weak var UserAge: UILabel!
#IBOutlet weak var UserPeople: UILabel!
var localNickname: String = ""
var remoteNickname: String = ""
#IBAction func SendMessage(_ sender: Any) {
print("SendMessage")
//print(localNickName)
//print(UserNickName.text!)
}
#IBAction func SendVideoCall(_ sender: Any) {
print("SendVideoCall")
let entityDescription = NSEntityDescription.entity(forEntityName: "Profile", in: managedObjectContext)
let request = NSFetchRequest<NSFetchRequestResult>()
request.entity = entityDescription
do {
let objects = try managedObjectContext.fetch(request)
if objects.count > 0 {
let match = objects[0] as! NSManagedObject
localNickname = match.value(forKey: "nick") as! String
} else {
print("Nothing founded")
}
} catch {
print("error")
}
remoteNickname = UserNickName.text!
socketdelegate?.startCall(localNickname: localNickname, remoteNickname: remoteNickname)
delegate?.VideoChatSegue()
}
}
UIViewcontroller Code
class ViewController: UIViewcontroller, StartCallDelegate {
var localNickname: String = ""
var remoteNickname: String = ""
override func viewDidLoad() {
super.viewDidLoad()
print(localNickname)
print(remoteNickname)
}
func startCall(localNickname: String, remoteNickname: String) {
print("Action startcall func")
self.localNickname = localNickname
self.remoteNickname = remoteNickname
}
startCall func not working
You need to define delegate in viewcontroller' ViewDidLoad
let objOardView = CardView() // this is only test purpose
objOardView.socketdelegate = self
I defined a custom cell layout as shown below:
I then added the desired values to my Firebase database as shown below:
However, after modifying the code to get the desired values from the firebase database I am getting an exception. When I run it in debug I see that it is just skipping over the first line in the code below, therefore the array is empty and hence it throws the exception. I am still very new to Firebase and Swift. I am following this example http://www.appcoda.com/firebase/ to get my own results and I am now stuck at this issue. I'll appreciate any help. I am providing all of the code below.
//Populate array
ServiceHistoryFBService.firebaseDBService.SERVICE_HISTORY_FOR_CURRENT_USER_REF.observeEventType(.Value, withBlock: { snapshot in
// The snapshot is a current look at our jokes data.
print(snapshot.value)
self.orderHistoryArray = []
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
// Make our jokes array for the tableView.
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let serviceOrder = ServiceOrder(key: key, dictionary: postDictionary)
// Items are returned chronologically, but it's more fun with the newest jokes first.
self.orderHistoryArray.insert(serviceOrder, atIndex: 0)
}
}
}
// Be sure that the tableView updates when there is new data.
self.tableView.reloadData()
})
I defined the Custom Cell as follows:
import UIKit
class SummaryCustomTableViewCell: UITableViewCell {
#IBOutlet weak var serviceOrderSummaryLabel: UILabel!
#IBOutlet weak var dateLabel: UILabel!
#IBOutlet weak var date: UILabel!
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
#IBOutlet weak var label3: UILabel!
#IBOutlet weak var label4: UILabel!
#IBOutlet weak var label5: UILabel!
#IBOutlet weak var label6: UILabel!
#IBOutlet weak var label7: UILabel!
#IBOutlet weak var label8: UILabel!
#IBOutlet weak var label9: UILabel!
#IBOutlet weak var label10: UILabel!
#IBOutlet weak var label11: UILabel!
#IBOutlet weak var label12: UILabel!
#IBOutlet weak var label13: UILabel!
#IBOutlet weak var label14: UILabel!
#IBOutlet weak var more: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
In my ViewController I am getting the snapshot from the Firebase database as follows by referencing these example:
http://www.appcoda.com/firebase/
import UIKit
import Firebase
class ServiceHistoryTableViewController: UITableViewController {
//Vars
var orderHistoryArray = [ServiceOrder]()
override func viewDidLoad() {
super.viewDidLoad()
//Populate array
ServiceHistoryFBService.firebaseDBService.SERVICE_HISTORY_FOR_CURRENT_USER_REF.observeEventType(.Value, withBlock: { snapshot in
// The snapshot is a current look at our jokes data.
print(snapshot.value)
self.orderHistoryArray = []
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
// Make our jokes array for the tableView.
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let serviceOrder = ServiceOrder(key: key, dictionary: postDictionary)
// Items are returned chronologically, but it's more fun with the newest jokes first.
self.orderHistoryArray.insert(serviceOrder, atIndex: 0)
}
}
}
// Be sure that the tableView updates when there is new data.
self.tableView.reloadData()
})
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return orderHistoryArray.count
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("customSummaryCell", forIndexPath: indexPath) as! SummaryCustomTableViewCell
cell.serviceOrderSummaryLabel.text = "SERVICE ORDER SUMMARY"
cell.dateLabel.text = "Created:"
if (orderHistoryArray[1].createdTimestamp.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.date.text = orderHistoryArray[0].createdTimestamp
}
if (orderHistoryArray[1].groceriesPickup.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.date.text = "Groceries Pickup"
}
if (orderHistoryArray[2].laundryDropoff.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.label1.text = "Laundry Dropoff"
}
if (orderHistoryArray[3].laundryPickup.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.label1.text = "Laundry Pickup"
}
if (orderHistoryArray[4].mealDelivery.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.label1.text = "Meal Delivery"
}
if (orderHistoryArray[5].petSiting.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.label1.text = "Pet Siting"
}
if (orderHistoryArray[6].petBathing.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.label1.text = "Pet Bathing"
}
if (orderHistoryArray[7].petFeeding.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.label1.text = "Pet Feeding"
}
if (orderHistoryArray[8].petWalking.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.label1.text = "Pet Walking"
}
if (orderHistoryArray[9].carpetCleaning.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.label1.text = "Carpet Cleaning"
}
if (orderHistoryArray[10].windowCleaning.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.label1.text = "Window Cleaning"
}
if (orderHistoryArray[11].carCleaning.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.label1.text = "Car Cleaning"
}
if (orderHistoryArray[12].yardCleaning.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.label1.text = "Yard Cleaning"
}
if (orderHistoryArray[13].lawnMowing.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.label1.text = "Lawn Mowing"
}
if (orderHistoryArray[14].courierServicing.isEmpty) {
cell.date.text = "Not selected"
} else {
cell.label1.text = "Courier Servicing"
}
cell.more.text = "More..."
return cell
}
}
Below is the code for the ServiceHistoryFBService file which is referenced in the ViewController
import Foundation
import Firebase
class ServiceHistoryFBService {
static let firebaseDBService = ServiceHistoryFBService()
private var _BASE_REF = Firebase(url: "\(BASE_URL)")
private var _SERVICE_HISTORY_FOR_CURRENT_USER_REF = Firebase(url: "\(BASE_URL)/service_history/uid")
var BASE_REF: Firebase {
return _BASE_REF
}
var SERVICE_HISTORY_FOR_CURRENT_USER_REF: Firebase {
return _SERVICE_HISTORY_FOR_CURRENT_USER_REF
}
}
Lastly, below is the code for the ServiceOrder file which is also referenced in the ViewController
import Foundation
import Firebase
class ServiceOrder: NSObject {
//Autogenerated Firebase ID (Order No.)
var key: String
//Service Order/Request Creation Timestamp
var createdTimestamp: String
var groceriesPickup: String
var laundryDropoff: String
var laundryPickup: String
var mealDelivery: String
var petSiting: String
var petBathing: String
var petFeeding: String
var petWalking: String
var carpetCleaning: String
var windowCleaning: String
var carCleaning: String
var yardCleaning: String
var lawnMowing: String
var courierServicing: String
override init() {
self.key = ""
//Service Order Creation Timestamp
self.createdTimestamp = ""
self.groceriesPickup = "N"
self.laundryDropoff = "N"
self.laundryPickup = "N"
self.mealDelivery = "N"
self.petSiting = "N"
self.petBathing = "N"
self.petFeeding = "N"
self.petWalking = "N"
self.carpetCleaning = "N"
self.windowCleaning = "N"
self.carCleaning = "N"
self.yardCleaning = "N"
self.lawnMowing = "N"
self.courierServicing = "N"
}
init(key: String, createdTimestamp: String,
groceriesPickup: String,
laundryDropoff: String,
laundryPickup: String,
mealDelivery: String,
petSiting: String,
petBathing: String,
petFeeding: String,
petWalking: String,
carpetCleaning: String,
windowCleaning: String,
carCleaning: String,
yardCleaning: String,
lawnMowing: String,
courierServicing: String) {
self.key = key
self.createdTimestamp = createdTimestamp
self.groceriesPickup = groceriesPickup
self.laundryDropoff = laundryDropoff
self.laundryPickup = laundryPickup
self.mealDelivery = mealDelivery
self.petSiting = petSiting
self.petBathing = petBathing
self.petFeeding = petFeeding
self.petWalking = petWalking
self.carpetCleaning = carpetCleaning
self.windowCleaning = windowCleaning
self.carCleaning = carCleaning
self.yardCleaning = yardCleaning
self.lawnMowing = lawnMowing
self.courierServicing = courierServicing
}
// Return a Dictionary<String, Bool> from ServiceOrder object
init(key: String, dictionary: Dictionary<String, AnyObject>){
self.key = key
self.createdTimestamp = dictionary["createdTimestamp"] as! String
self.groceriesPickup = dictionary["groceriesPickup"] as! String
self.laundryDropoff = dictionary["laundryDropoff"] as! String
self.laundryPickup = dictionary["laundryPickup"] as! String
self.mealDelivery = dictionary["mealDelivery"] as! String
self.petSiting = dictionary["petSiting"] as! String
self.petBathing = dictionary["petBathing"] as! String
self.petFeeding = dictionary["petFeeding"] as! String
self.petWalking = dictionary["petWalking"] as! String
self.carpetCleaning = dictionary["] carpetCleaning"] as! String
self.windowCleaning = dictionary["windowCleaning"] as! String
self.carCleaning = dictionary["carCleaning"] as! String
self.yardCleaning = dictionary["yardCleaning"] as! String
self.lawnMowing = dictionary["lawnMowing"] as! String
self.courierServicing = dictionary["courierServicing"] as! String
}
}
In your "ServiceHistoryFBService" file you have this line
private var _SERVICE_HISTORY_FOR_CURRENT_USER_REF = Firebase(url: "\(BASE_URL)/service_history/uid")
With this Firebase reference you are looking for the path "/sample_project/service_history/uid", which value is NSNull because you are hardcoding an extra "uid" child at the end, your path should be "/sample_project/service_history". If you want to access the service_history of the currently logged in user you can do something like this:
If you are using the Firebase Legacy Console
if let authData = ServiceHistoryFBService.firebaseDBService._REF_BASE.authData{
ServiceHistoryFBService.firebaseDBService.SERVICE_HISTORY_FOR_CURRENT_USER_REF.childByAppendingPath(authData.uid)
.observeEventType //etc
}
If you are using the new Firebase Console released at Google I/O 2016 is almost the same but you need to get the user like this:
if let user = FIRAuth.auth()?.currentUser {
ServiceHistoryFBService.firebaseDBService.SERVICE_HISTORY_FOR_CURRENT_USER_REF.child(user.uid)
.observeEventType //etc
}
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