• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 带有成功和失败的 Swift 方法链

[复制链接]
菜鸟教程小白 发表于 2022-12-11 17:12:29 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在尝试在我的代码中为成功和失败调用实现方法链接,但我似乎无法真正调用 onSuccess 方法。

  1. View Controller 调用 getProduct(_ 函数。
  2. getProduct(_ 进行 API 调用,然后使用检索到的 json 调用 storeProduct(_
  3. storeProduct(_ 调用 fetchProduct(_
  4. fetchProduct(_ 调用 doSuccess(_ 但这永远不会回到先前调用的 onSuccess 中。<

一些代码片段

BSProductChainable.swift

import Foundation

class BSProductChainable<SuccessParams, FailureParams> {

    var successClosure: ((SuccessParams) -> ())? = nil
    var failureClosure: ((FailureParams) -> ())? = nil

    func onSuccess(closure: (SuccessParams) -> ()) -> BSProductChainable {
        successClosure = closure
        return self
    }
    func onFailure(closure: (FailureParams) -> ()) -> BSProductChainable {
        failureClosure = closure
        return self
    }
    func doSuccess(params: SuccessParams) {
        if let closure = successClosure {
            closure(params)
        }
    }
    func doFailure(params: FailureParams) {
        if let closure = failureClosure {
            closure(params)
        }
    }
}

BSProductManagerSwift.swift

class BSProductManagerSwift: NSObject {

typealias productResponseChain = BSProductChainable<roduct, NSError?>
typealias productsResponseChain = BSProductChainable<[Product], NSError?>

var serviceClient: BSNetworkingServiceClient!
var objectContext: NSManagedObjectContext!
var productChains: BSProductChainable<roduct, NSError?>!
var productsChains: BSProductChainable<[Product], NSError?>!

convenience init(serviceClient: BSNetworkingServiceClient) {
    self.init()
    self.serviceClient = serviceClient
    self.objectContext = managedObjectContext
    self.productChains = BSProductChainable<roduct, NSError?>()
    self.productsChains = BSProductChainable<[Product], NSError?>()
}

func getProduct(ean: String) -> productResponseChain {

    let urlString = BSConstants.BarcodeScanner.productEndpoint.stringByAppendingString(ean)
    serviceClient.GET(urlString, failure: { (error) in
        print("Could not get product")
    }) { (response) in
        if let json = response {
            self.storeProduct(json).onSuccess({ (returedProduct) in
                print("Stored product")
            })
        }
    }

    return productChains
}

func storeProduct(json: JSON) -> productResponseChain {

    fetchProduct(json["ean"].stringValue).onSuccess { (returedProduct) in
        self.productChains.doSuccess(returedProduct)
    }

    return productChains
}

func fetchProduct(ean: String) -> productResponseChain {

    let fetchRequest = NSFetchRequest(entityName: "roduct")
    let predicateEAN = NSPredicate(format: "%K == %@", "ean", ean)
    let predicateMarket = NSPredicate(format: "%K == %@", "market", BSCountryManager.sharedInstance().getCurrentCountry().market)
    let predicateLocale = NSPredicate(format: "%K == %@", "locale", BSLocalizationManager.sharedManager().currentLocalization.localeIdentifier())
    let predicateCurrency = NSPredicate(format: "%K == %@", "currency", BSLocalizationManager.sharedManager().currentLocalization.country.currencyIdentifierDMW)
    let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateEAN, predicateMarket, predicateLocale, predicateCurrency])
    fetchRequest.predicate = compoundPredicate

    do {
        let matchingProuducts = try objectContext.executeFetchRequest(fetchRequest)

        if matchingProuducts.count == 0 {
            print("No matching products found")
            let entity = NSEntityDescription.entityForName("roduct", inManagedObjectContext: objectContext)
            productChains.doSuccess(Product(entity: entity!, insertIntoManagedObjectContext: objectContext))
        } else {
            print("Found matching product")
            let d = matchingProuducts.first as! Product
            productChains.doSuccess(d)
        }
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
        productChains.doFailure(error)
    }

    return productChains
}

我最初为每个函数初始化了可链接类,但这有其自身的问题,我认为(可能是错误的)我应该只初始化可链接类一次并传递它的引用。

关于我哪里出错/接下来我可以尝试什么的一些输入会很棒。



Best Answer-推荐答案


根据@john elements 的建议,我决定使用 PromiseKit

这不需要太多的代码更改,下面是函数现在的样子(仍然需要做一些代码清理,但它可以工作!):<​​/p>

func getProduct(ean: String) -> Promise<roduct> {
    return Promise { fullfill, reject in
        let urlString = BSConstants.BarcodeScanner.productEndpoint.stringByAppendingString(ean)
        serviceClient.GET(urlString, failure: { (error) in
            reject(error!)
        }) { (response) in
            if let json = response {
                self.storeProduct(json).then ({ returnedProduct in
                    print("We stored the product: \(returnedProduct.ean)")
                    fullfill(returnedProduct)
                }).error { returnedError in
                    print("We had a problem storing the product: \(returnedError)")
                }
            }
        }
    }
}

func storeProduct(json: JSON) -> Promise<roduct> {
    return Promise { fullfill, reject in
        fetchProduct(json["ean"].stringValue).then ({ returnedProduct in

            var storedProduct: Product!
            var isNewProduct = false

            print("Fetched Product: \(returnedProduct.ean)")

            isNewProduct = returnedProduct.valueForKey("ean") == nil
            storedProduct = returnedProduct
            storedProduct.setValue(json["name"].stringValue, forKey: "name")
            storedProduct.setValue(json["ean"].stringValue, forKey: "ean")
            storedProduct.setValue(json["image"].stringValue, forKey: "image")
            storedProduct.setValue(json["price"].doubleValue, forKey: "price")
            storedProduct.setValue(json["status"].intValue, forKey: "status")
            storedProduct.setValue(json["pdp"].stringValue, forKey: "pdp")
            storedProduct.setValue(BSCountryManager.sharedInstance().getCurrentCountry().market, forKey: "market")
            storedProduct.setValue(BSLocalizationManager.sharedManager().currentLocalization.localeIdentifier(), forKey: "locale")
            storedProduct.setValue(BSLocalizationManager.sharedManager().currentLocalization.country.currencyIdentifierDMW, forKey: "currency")

            do {
                try self.objectContext.save()
                print("Stored Product: \(returnedProduct.ean)")
                fullfill(returnedProduct)

                if isNewProduct {
                    NSNotificationCenter.defaultCenter().postNotificationName("DidAddScanEntry", object: nil)
                }

            } catch let error as NSError {
                print("Could not save \(error), \(error.userInfo)")
                reject(error)
            }

        }).error { returnedError in
            print("We had a problem fetching the product: \(returnedError)")
            reject(returnedError)
        }
    }
}

func fetchProduct(ean: String) -> Promise<roduct> {
    return Promise { fullfill, reject in

        let fetchRequest = NSFetchRequest(entityName: "roduct")
        let predicateEAN = NSPredicate(format: "%K == %@", "ean", ean)
        let predicateMarket = NSPredicate(format: "%K == %@", "market", BSCountryManager.sharedInstance().getCurrentCountry().market)
        let predicateLocale = NSPredicate(format: "%K == %@", "locale", BSLocalizationManager.sharedManager().currentLocalization.localeIdentifier())
        let predicateCurrency = NSPredicate(format: "%K == %@", "currency", BSLocalizationManager.sharedManager().currentLocalization.country.currencyIdentifierDMW)
        let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateEAN, predicateMarket, predicateLocale, predicateCurrency])
        fetchRequest.predicate = compoundPredicate

        do {
            let matchingProuducts = try objectContext.executeFetchRequest(fetchRequest)

            if matchingProuducts.count == 0 {
                print("No matching products found")
                let entity = NSEntityDescription.entityForName("roduct", inManagedObjectContext: objectContext)
                fullfill(Product(entity: entity!, insertIntoManagedObjectContext: objectContext))
            } else {
                print("Found matching product")
                let d = matchingProuducts.first as! Product
                fullfill(d)
            }
        } catch let error as NSError {
            print("Could not fetch \(error), \(error.userInfo)")
            reject(error)
        }
    }
}

关于ios - 带有成功和失败的 Swift 方法链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38832681/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap