gpt4 book ai didi

ios - 从 Firebase Swift 下载时函数循环

转载 作者:行者123 更新时间:2023-11-29 05:45:07 25 4
gpt4 key购买 nike

我突然从 Firebase 下载用户目录的函数中得到一些奇怪的结果。在控制台打印中,我看到该函数打印了 5 次,这意味着该函数正在循环。我正在从 Firebase 存储异步下载产品图片。我在第一次登录时级联调用此函数,以获取用户的详细信息、订单、销售额等。我是为了满足用户更换iPad的需要而想到这个选项的。

你能看到函数在哪里循环了 5 次吗?

这是函数:

static func downloadProducts(completed: @escaping (Bool) -> (), vendor: String) {
print("Firebase.downloadProducts() : Query for products in Firebase started")
let ref = Database.database().reference()
ref.child("Continent").child("Europe").child("Country").child("\(UserDetails.country!)").child("Catalog").queryOrdered(byChild: "Product Vendor").queryEqual(toValue: String(describing: UserDetails.fullName!)).observeSingleEvent(of: .value) { (snapshot) in
print("downloadProducts() : snapshot is: \(snapshot)")
guard let data = snapshot.value as? [String: [String : String]] else { print("downloadProducts() : data is not [String: [String : String]] "); return}
// guard let data = snapshot.value as? [String : String] else { print("downloadProducts() : wrong type of data"); return}
for (_, value) in data {

let productId = value["Product Id"]!
let vendor = value["Product Vendor"]!
let availableQuantity = value["Available Quantity"]!
let soldQuantity = value["Sold Quantity"]!
let minimumStock = value["Minimum Stock"]!
let name = value["Product Name"]!
let price = value["Product Price"]!
let category = value["Product Category"]!
let description = value["Product Description"]!
let pictureUrl = value["Product Picture Url"]!
let url = URL(string: pictureUrl)!
DispatchQueue.global().async {
let data = try? Data(contentsOf : url)
DispatchQueue.main.async {

let productImage = UIImage(data: data!)!
do{
try Product.saveProduct(completed: { (true) in
print("Firebase.downloadProducts() : Product from Firebase added to CoreData")
}, productImage: productImage, productId: productId, category: category, name: name, price: price, vendor: vendor, availableQuantity: availableQuantity, soldQuantity: soldQuantity, minimumStock: minimumStock, description: description)
} catch {
print("Firebase.downloadProducts() : Error saving product to CoreData: \(error)")
}
}
print("downloadProducts() : User inventory found in Firebase and saved to CoreData")
print("downloadProducts() : Query for products in Firebase ended")
completed(true)
}
}
}
}

这是级联调用:

static func findUser(userName: String)  {
print("findUser(): checkinf for User in CoreData")
let context = CoreData.databaseContext
let request: NSFetchRequest<User> = User.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: false),NSSortDescriptor(key: "logo", ascending: false)]
request.predicate = NSPredicate(format: "name == %@", userName)
do {
let fetch = try context.fetch(request)
if fetch.count > 0 {
print(" findUser() : User is a returning user")
for value in fetch { // user exists
UserDetails.shopId = value.shopId
UserDetails.fullName = value.name
UserDetails.logo = UIImage(data: value.logo! as Data )
UserDetails.logoUrl = value.logoUrl
UserDetails.address = value.address
UserDetails.zipCode = value.zipCode
UserDetails.city = value.city
UserDetails.region = value.region
UserDetails.country = value.country
UserDetails.phoneNumber = value.phoneNumber
UserDetails.latitude = value.latidute
UserDetails.longitude = value.longitude
}
} else {
print(" findUser(): User is a 1st time user in device, will now check for user in Firebase")
Firebase.downloadShopDetails(completed: { (true) in
if UserDetails.shopId == nil {
// user is not registered in Firebase
print("findUser() : User not found in Firebase, user is First time user ")
} else {
// user has been found in Firebase
print("findUser() : user found in Firebase, will now check for opening times in Firebase")
Firebase.downloadOpeningTimes(completed: { (true) in

print("findUser() : Opening times downloaded from Firebase, will now check for user orders in Firebase")
Firebase.downloadOrders(completed: { (true) in

print("findUser() : user orders downloaded from Firebase, will now check for user products in Firebase")
Firebase.downloadProducts(completed: { (true) in
print("findUser() : Inventoy downloaded from Firebase")
}, vendor: UserDetails.fullName!)

})

}, shopName: UserDetails.fullName!)

}
}, shopName: userName)
UserDetails.shopId = UUID().uuidString
UserDetails.fullName = userName
}
} catch {
print("findUser(): Error loading user details : \(error)")
}
}

最佳答案

您在这里多次调用完成

DispatchQueue.global().async {
let data = try? Data(contentsOf : url)
DispatchQueue.main.async {

let productImage = UIImage(data: data!)!
do{
try Product.saveProduct(completed: { (true) in
print("Firebase.downloadProducts() : Product from Firebase added to CoreData")
}, productImage: productImage, productId: productId, category: category, name: name, price: price, vendor: vendor, availableQuantity: availableQuantity, soldQuantity: soldQuantity, minimumStock: minimumStock, description: description)
} catch {
print("Firebase.downloadProducts() : Error saving product to CoreData: \(error)")
}
}
print("downloadProducts() : User inventory found in Firebase and saved to CoreData")
print("downloadProducts() : Query for products in Firebase ended")
completed(true)
}

但你应该

let g = DispatchGroup() 
for (_, value) in data {
...
...
...
DispatchQueue.global().async {
g.enter()
let data = try? Data(contentsOf : url)
DispatchQueue.main.async {

let productImage = UIImage(data: data!)!
do{
try Product.saveProduct(completed: { (true) in
print("Firebase.downloadProducts() : Product from Firebase added to CoreData")
}, productImage: productImage, productId: productId, category: category, name: name, price: price, vendor: vendor, availableQuantity: availableQuantity, soldQuantity: soldQuantity, minimumStock: minimumStock, description: description)
} catch {
print("Firebase.downloadProducts() : Error saving product to CoreData: \(error)")
}
}
print("downloadProducts() : User inventory found in Firebase and saved to CoreData")
print("downloadProducts() : Query for products in Firebase ended")
g.leave()
}

}
g.notify(queue:.main) {
completed(true)
}

关于ios - 从 Firebase Swift 下载时函数循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56226106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com