【问题标题】:Swift 3 code rewritten from Objective-C doesn't work从 Objective-C 重写的 Swift 3 代码不起作用
【发布时间】:2017-09-29 17:14:23
【问题描述】:

所以我在 Objective-C 中有这段代码,我需要重写为 Swift3。

但它似乎不起作用。下面是 Objective-C,我将其重写为 Swift3:

Objective-C

- (void)handleMobilePayPaymentWithUrl:(NSURL *)url
{
    [[MobilePayManager sharedInstance]handleMobilePayPaymentWithUrl:url success:^(MobilePaySuccessfulPayment * _Nullable mobilePaySuccessfulPayment) {
        NSString *orderId = mobilePaySuccessfulPayment.orderId;
        NSString *transactionId = mobilePaySuccessfulPayment.transactionId;
        NSString *amountWithdrawnFromCard = [NSString stringWithFormat:@"%f",mobilePaySuccessfulPayment.amountWithdrawnFromCard];
        NSLog(@"MobilePay purchase succeeded: Your have now paid for order with id '%@' and MobilePay transaction id '%@' and the amount withdrawn from the card is: '%@'", orderId, transactionId,amountWithdrawnFromCard);
        [ViewHelper showAlertWithTitle:@"MobilePay Succeeded" message:[NSString stringWithFormat:@"You have now paid with MobilePay. Your MobilePay transactionId is '%@'", transactionId]];

    } error:^(NSError * _Nonnull error) {
        NSDictionary *dict = error.userInfo;
        NSString *errorMessage = [dict valueForKey:NSLocalizedFailureReasonErrorKey];
        NSLog(@"MobilePay purchase failed:  Error code '%li' and message '%@'",(long)error.code,errorMessage);
        [ViewHelper showAlertWithTitle:[NSString stringWithFormat:@"MobilePay Error %li",(long)error.code] message:errorMessage];

        //TODO: show an appropriate error message to the user. Check MobilePayManager.h for a complete description of the error codes

        //An example of using the MobilePayErrorCode enum
        //if (error.code == MobilePayErrorCodeUpdateApp) {
        //    NSLog(@"You must update your MobilePay app");
        //}
    } cancel:^(MobilePayCancelledPayment * _Nullable mobilePayCancelledPayment) {
        NSLog(@"MobilePay purchase with order id '%@' cancelled by user", mobilePayCancelledPayment.orderId);
        [ViewHelper showAlertWithTitle:@"MobilePay Canceled" message:@"You cancelled the payment flow from MobilePay, please pick a fruit and try again"];

    }];
}

还有我的 Swift3 重写:

func handleMobilePayPayment(with url: URL) {
        MobilePayManager.sharedInstance().handleMobilePayPayment(with: url, success: {( mobilePaySuccessfulPayment: MobilePaySuccessfulPayment?) -> Void in
            let orderId: String = mobilePaySuccessfulPayment!.orderId
            let transactionId: String = mobilePaySuccessfulPayment!.transactionId
            let amountWithdrawnFromCard: String = "\(mobilePaySuccessfulPayment!.amountWithdrawnFromCard)"
            print("MobilePay purchase succeeded: Your have now paid for order with id \(orderId) and MobilePay transaction id \(transactionId) and the amount withdrawn from the card is: \(amountWithdrawnFromCard)")
                self.alert(message: "You have now paid with MobilePay. Your MobilePay transactionId is \(transactionId)", title: "MobilePay Succeeded")

        }, error: {( error: Error?) -> Void in
            let dict: [AnyHashable: Any]? = error?.userInfo
            let errorMessage: String? = (dict?.value(forKey: NSLocalizedFailureReasonErrorKey) as? String)
            print("MobilePay purchase failed:  Error code '(Int(error?.code))' and message '(errorMessage)'")
            self.alert(message: errorMessage!, title: "MobilePay Error \(error?.code as! Int)")
            self.alert(message: error as! String)
            //TODO: show an appropriate error message to the user. Check MobilePayManager.h for a complete description of the error codes
            //An example of using the MobilePayErrorCode enum
            //if (error.code == MobilePayErrorCodeUpdateApp) {
            //    NSLog(@"You must update your MobilePay app");
            //}
        }, cancel: {(_ mobilePayCancelledPayment: MobilePayCancelledPayment?) -> Void in
            print("MobilePay purchase with order id \(mobilePayCancelledPayment?.orderId!) cancelled by user")
            self.alert(message: "You cancelled the payment flow from MobilePay, please pick a fruit and try again", title: "MobilePay Canceled")
        })
    }

我遇到的问题是中间的error,如下图所示。

我不确定自己做错了什么以及如何让 userInfo 和错误信息“脱离”错误。

提前致谢!

【问题讨论】:

    标签: objective-c xcode swift3


    【解决方案1】:

    你必须将演员 error 桥接到 NSError

    ...
    }, error: { error in   // according to the ObjC code error is non-optional 
        let nsError =  error as NSError   
        let userInfo = nsError.userInfo as! [String:Any]
        let errorMessage = userInfo[NSLocalizedFailureReasonErrorKey] as! String
        ...
        self.alert(message: errorMessage, title: "MobilePay Error \(nsError.code)")
    

    基本上不注释编译器可以推断的类型,并且从不使用valueForKey 从用户信息字典中获取值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-16
      • 1970-01-01
      • 2018-04-08
      相关资源
      最近更新 更多