简体   繁体   English

Swift确实捕获内部功能不起作用

[英]Swift do catch inside function doesn't work

I have a function which parses JSON, but I get a nil error dealing with the URL strings: 我有一个解析JSON的函数,但是在处理URL字符串时出现零错误:

var jsonResponse: NSMutableDictionary?
do{
    jsonResponse = try NSJSONSerialization.JSONObjectWithData(data!,
        options: NSJSONReadingOptions.AllowFragments) as? NSMutableDictionary;

    let info : NSArray =  jsonResponse!.valueForKey("latest_receipt_info") as! NSArray
    let transaction_id: String? = info[0].valueForKey("transaction_id") as? String
    let purchase_date: String? = info[0].valueForKey("purchase_date") as? String
    let product_id: String? = info[0].valueForKey("product_id") as? String
    let web_order_line_item_id: String? = info[0].valueForKey("web_order_line_item_id") as? String

    print("test")

    // Send Values  

    let addIAPUrl:NSString = "http://bla.com/application/addIAP.php?transaction_id=\(transaction_id!)&purchase_date=\(purchase_date)&product_id=\(product_id)&web_order_line_item_id=\(web_order_line_item_id)&userID=\(prefs.valueForKey("userID") as! String!)"
   self.apiRequests(addIAPUrl as String, completionHandler: { (success, message) -> Void in

             print("success \(addIAPUrl)")

        if(success == 1){

            dispatch_async(dispatch_get_main_queue()){

                // ADDED
                print("success \(addIAPUrl)")

            }

        }else{

           // DONT ADDED
        }



    })

The output doesn't return any error but the function fails after print("test") . 输出没有返回任何错误,但是函数在print(“ test”)之后失败。 The apiRequests function works in other cases, but doesn't seem to work in this context. apiRequests函数在其他情况下也可以使用,但在这种情况下似乎不起作用。

I would appreciate any help finding the problem. 如果能找到问题,我将不胜感激。

Here is the code for the apiRequest function: 这是apiRequest函数的apiRequest

func apiRequests(url : String, completionHandler : ((success : Int, message : String) -> Void)) {

      guard let url = NSURL(string: url as String) else {

          return
      }

      let urlRequest = NSURLRequest(URL: url)
      let config = NSURLSessionConfiguration.defaultSessionConfiguration()
      let session = NSURLSession(configuration: config)

      let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (data,  response, error) in
          guard let responseData = data else {

              return
          }
          guard error == nil else {

              print(error)
              return
          }

          let post: NSDictionary
          do {
              post = try NSJSONSerialization.JSONObjectWithData(responseData,
                  options: []) as! NSDictionary
          } catch  {

              return
          }

          let numberFromString = Int((post["success"] as? String)!)


          completionHandler(success: (numberFromString)!, message: (post["message"] as? String)!)



      })
      task.resume()

  }

It seems to me that the problem is most likely that your apiRequests: function is erroring at one of many places, and is returning instead of calling your callback with an error state. 在我看来,问题很可能是您的apiRequests:函数在许多位置之一出错,并且返回而不是以错误状态调用回调。

func apiRequests(url : String, completionHandler : ((success : Int, message : String) -> Void)) {

    guard let url = NSURL(string: url as String) else {
        completionHandler(0, "Couldn't get URL")
        return
    }

    let urlRequest = NSURLRequest(URL: url)
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config)

    let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (data,  response, error) in
        guard let responseData = data else {
            completionHandler(0, "Data was nil")
            return
        }
        guard error == nil else {
            print(error)
            completionHandler(0, "Error wasn't nil")
            return
        }

        let post: NSDictionary
        do {
            post = try NSJSONSerialization.JSONObjectWithData(responseData,
                options: []) as! NSDictionary
        } catch  {
            completionHandler(0, "Error with NSJSONSerialization")
            return
        }

        let numberFromString = Int((post["success"] as? String)!)


        completionHandler(success: (numberFromString)!, message: (post["message"] as? String)!)



    })
    task.resume()

}

Side note, but not related to the fix, 旁注,但与修复无关,

 let addIAPUrl:NSString = "http://bla.com/application/addIAP.php?transaction_id=\(transaction_id!)&purchase_date=\(purchase_date)&product_id=\(product_id)&web_order_line_item_id=\(web_order_line_item_id)&userID=\(prefs.valueForKey("userID") as! String!)"
 self.apiRequests(addIAPUrl as String, completionHandler: { (success, message) -> Void in

Can easily be replaced with 可以轻松替换为

let addIAPUrl = "http://bla.com/application/addIAP.php?transaction_id=\(transaction_id!)&purchase_date=\(purchase_date)&product_id=\(product_id)&web_order_line_item_id=\(web_order_line_item_id)&userID=\(prefs.valueForKey("userID") as! String!)"
self.apiRequests(addIAPUrl, completionHandler: { (success, message) -> Void in

Because you are converting a String to an NSString then back to a String 因为您是将String转换为NSString然后再转换 String

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

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