有人知道如何让用户名出现在商店里吗?
Posted
技术标签:
【中文标题】有人知道如何让用户名出现在商店里吗?【英文标题】:Anyone know how to make username appear on shop? 【发布时间】:2022-01-03 11:44:46 【问题描述】:制作购物车应用程序并遇到问题。我有一个登录页面,如果登录,它将存储在核心数据和登录中,但我想让用户名出现在另一个视图控制器的表视图上 登录VC:
import UIKit
import CoreData
class LoginVC: UIViewController
@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view
fetchData()
@IBAction func login(_ sender: Any)
for acc in userList
if username.text == acc.username && password.text == acc.password
currentUser = username.text!
try! context.save()
performSegue(withIdentifier: "DisplayShop1", sender: nil)
/*else if username.text == "" || password.text == "" || username.text != acc.username || password.text != acc.username
let alert = UIAlertController(title: "Alert", message: "Please enter the right credentials", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
*/
func fetchData()
userList = try! context.fetch(User.fetchRequest())
ListingShopVC
import UIKit
import CoreData
class ListingShopVC: UIViewController, UITableViewDelegate, UITableViewDataSource
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var usernameloggedin: UILabel!
@IBOutlet weak var creditsdisplay: UILabel!
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var myUser:[User] = []
var mySecond:[Product] = []
var mySecondF:[Product] = []
var id:String = ""
var name:String = ""
var price:Double = 0.0
var image:String = ""
var details:String = ""
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad()
super.viewDidLoad()
fetch()
tableView.delegate = self
tableView.dataSource = self
extracted()
usernameloggedin.text = "Welcome \(userList)"
creditsdisplay.text = "You have \(userList)"
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int
// #warning Incomplete implementation, return the number of sections
return 1
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
// #warning Incomplete implementation, return the number of rows
return mySecond.count
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "hello", for: indexPath) as! TableCellData
// Configure the cell...
cell.shopTitle.text = mySecond[indexPath.row].name
cell.shopPrice.text = "$" + String(mySecond[indexPath.row].price) + "0"
cell.shopDesc.text = mySecond[indexPath.row].description
if let imageURL = URL(string: mySecond[indexPath.row].image)
DispatchQueue.global().async
let data = try? Data(contentsOf: imageURL)
if let data = data
let image = UIImage(data: data)
DispatchQueue.main.async
cell.shopImageView.image = image
return cell
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
id = mySecond[indexPath.row].id
name = mySecond[indexPath.row].name
price = mySecond[indexPath.row].price
image = mySecond[indexPath.row].image
//print("At table \(image)")
details = mySecond[indexPath.row].description
performSegue(withIdentifier: "toDetails", sender: self)
override func prepare(for segue: UIStoryboardSegue, sender:Any?)
if segue.identifier == "toDetails"
let vc = segue.destination as! ProductDetail
vc.productID = id
vc.productName = name
vc.productPrice = price
vc.productPicture = image
vc.productDetails = details
print(vc.productDetails)
func extracted()
guard let url = URL(string: "http://rajeshrmohan.com/sport.json")
else return
let task = URLSession.shared.dataTask(with: url)
(data,response,error) in
guard let dataResponse = data,
error == nil else
print(error?.localizedDescription ?? "Response Error")
return
do
let decoder = JSONDecoder()
let model:[Product] = try decoder.decode([Product].self, from: dataResponse)
//print(model)
for i in 0..<model.count
self.mySecond.append(model[i])
DispatchQueue.main.async
self.tableView.reloadData()
catch let parsingError
print("Error", parsingError)
task.resume()
@IBAction func logOut(_ sender: Any)
func fetch()
userList = try! context.fetch(User.fetchRequest())
tableView.reloadData()
上半部分https://i.stack.imgur.com/9RahD.jpg
我只是想让它出现在顶部也似乎我的登录页面和代码不能正常工作如果我放一个 if 空所以如果有任何可能的建议将不胜感激
【问题讨论】:
您在错误的地方将用户名设置为相应的文本字段。 【参考方案1】:据我了解,您无法在页面之间传递数据。将此添加到您从中获取 userList 的页面。
@IBAction func okAction(_ sender: Any)
let controller = storyboard?.instantiateViewController(withIdentifier: "DisplayShop1") as! ListingShopVC
controller.userList = userList
controller.modalPresentationStyle = .fullScreen
present(controller, animated: true, completion: nil)
如果你将这个添加到稍后要传输的用户列表的页面,你可以调用用户列表。
var userList: String = ""
【讨论】:
我的用户列表基本上是一个存储用户实体的数组,它包含一个 swift 文件: import Foundation var userList:[User] = [] var myCart:[Cart] = [] var currentUser:String = "" 变量总数:双 = 0.0【参考方案2】:你几乎拥有它。不是将用户名传递到字符串中,而是传递整个 Core Data 对象列表,这些对象被格式化为字符串,但不是以您想要的方式。您应该获取用户的用户名,然后将其传递到字符串中:
let username = userList.first?.username ?? ""
usernameloggedin.text = "Welcome \(username)"
creditsdisplay.text = "You have \(username)"
也就是说,这里有一些评论可以让这项工作更加可靠。
-
我会将这部分代码移至您的函数以从数据库加载。这样,如果您从数据库中重新加载数据,它将获得正确的用户,并且名称将得到适当的更新。
您应该选择一位正在购物的用户,并且只选择一位用户。目前,您正在获取用户列表并保留用户列表。也没有排序来确定使用哪个用户,因此它可能会在中间更改。为了解决这个问题,我建议您创建一个新属性来存储类型为
User
的当前用户,而不是[User]
,并且只从数据库中加载一个用户。获取请求将返回一个数组,因此您只需要获取并保留第一个。此外,为了使这更加可靠,您可能会考虑让您的第一个视图检查是否有用户登录,从数据库中获取该用户(您已经在这样做),并使用依赖注入将该用户传递到商店视图.有很多关于如何处理这个问题的教程,但基本上你会在prepareForSegue
调用中获得对第二个视图的引用,并将第二个视图上的用户属性设置为所需的用户,从而“注入你的依赖项”。
【讨论】:
以上是关于有人知道如何让用户名出现在商店里吗?的主要内容,如果未能解决你的问题,请参考以下文章