繁体   English   中英

从Firebase Swift下载时,函数循环

[英]Function loops when downloading from Firebase Swift

我突然从一个从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)
}

我终于找到了问题所在。在Firebase.downloadOrders()我将订单保存到Core Data时调用complete(true) ,因此对于保存的每个订单,调用了`Firebase.downloadProduct()。 在for循环中放置它,现在正确下载产品。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM