Utku Dalmaz
Utku Dalmaz

Reputation: 10172

Invalid conversion from throwing function of type Error when some code added

This code normally works well:

let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: NSURL(string: "http://example.com")!)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.HTTPMethod = "POST"
        let data = "devicetoken=\(devicetoken!)&userID=1"
        request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)

        let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

            if let response = response {

                let res = response as! NSHTTPURLResponse
                if (res.statusCode >= 200 && res.statusCode < 300)
                {

                    do {
                        let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSArray
                        let json = JSON(jsonData)

                        for (_, subJSON): (String, JSON) in json[0]["events"] {

                            let titlex = subJSON["title"].string
                            let guestx = subJSON["guests"].string

                            if let guestPicsArray = subJSON["guestpics"].array {
                                if (self.myarr.count > 0) {

                                    self.myarr.removeAll()

                                }

                                for item in guestPicsArray {
                                    if let title = item.string {
                                        self.myarr.append(title)
                                    }
                                }

                  let rel1 = InboxEvents(title: titlex!, guests: guestx!, eventresim: eventresimx!, eventID : NSInteger(eventIDx!)!, arr: self.myarr)
                  self.arrayOfRels.append(rel1)

                            }

                        }


                    } catch let error as NSError {
                        print(error)
                    }


                    dispatch_async(dispatch_get_main_queue(), {

                        self.tableView.reloadData()

                    })


                } else {
                    self.boxView.removeFromSuperview()
                    let alert = UIAlertController(title: "Sign in Failed!", message: "Connection Failed", preferredStyle: .Alert)

                    alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction) in

                    }))

                    self.presentViewController(alert, animated: true, completion: nil)
                }
            }  else if let error = error {
                print(error.localizedDescription)
        }
        })
        task.resume()

However, when I add this code to viewDidAppear I get the error:

Invalid conversion from throwing function of type '(_, _, _) throws -> ()' to non-throwing function type '(NSData?, NSURLResponse?, NSError?) -> Void'

for above code.

 if (PopupChat.instance().isUserLoaded == true) {
            let dialogsIDs: NSSet = NSSet(array: ["55fae39ca28f9a701d0058fb"])
            QBRequest.totalUnreadMessageCountForDialogsWithIDs(dialogsIDs as! Set<String>, successBlock: { (response: QBResponse, count: UInt, dialogs: [String : AnyObject]?) -> Void in
                let tabArray = self.tabBarController?.tabBar.items as NSArray!
                let tabItem = tabArray.objectAtIndex(3) as! UITabBarItem
                tabItem.badgeValue = String(count)
            }) { (response: QBResponse) -> Void in

            }
        }

Upvotes: 3

Views: 2558

Answers (1)

matt
matt

Reputation: 535230

Change

} catch let error as NSError {

to simple

} catch {

and that should fix it.

I suppose you'd also like to know why that fixes it? It's because your catch let error as NSError doesn't mean what you think it means. In particular, it does not count as a "catch-all" catch, so it fails to catch every possible error. Therefore the compiler complains because your anonymous function can throw, which is not permitted.

Upvotes: 8

Related Questions