Swift do catch inside 函数不起作用

Swift do catch inside function doesn't work

我有一个解析 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
        }



    })

输出没有 return 任何错误,但函数在 print("test") 后失败。 apiRequests 函数在其他情况下有效,但在这种情况下似乎无效。

如果能帮助我找到问题,我将不胜感激。

这里是 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()

  }

在我看来,问题很可能是您的 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()

}

旁注,但与修复无关,

 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

可以轻松替换为

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

因为您要将 String 转换为 NSString,然后 back 转换为 String