0

I'm trying to reuse a method to refresh a table view from a JSON file on internet. When I'm trying to call the same method more than once I got this error :

EXEC_BAD_INSTRUCTION (code=EXC_i386_INVOP,subcode=0x0)

Can some one tell me how to do it right ?

Thanks you.

func topRefresh(sender:AnyObject){
    self.notificationsDisplayed.removeAll()

    var list=Array<Notification>()

    //request json
    let url = NSURL(string: jsonLink)!
    let session = NSURLSession.sharedSession()

    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod="POST"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

    let paramString="username=Axel&password=test"
    request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = session.dataTaskWithRequest(request) {
        (data, response, error) -> Void in

        let httpResponse = response as! NSHTTPURLResponse

        if (httpResponse.statusCode == 200) {
            do{
                let jsonDict = try NSJSONSerialization.JSONObjectWithData(data!,options: .AllowFragments)

                list=self.parseJson(jsonDict)

            }catch {
                print("Error with Json: \(error)")
            }
        }else{
            print("HTTP Error")
        }

        //compare new data with past data

        while(list.count>0){
            let tmp=list.last
            for notification in self.notifications {
                if(tmp!.id==notification.severity){
                    list.removeLast()
                }else{
                    self.notifications.insert(tmp!, atIndex: 0)
                    list.removeLast()
                }
            }
        }

        self.notificationsDisplayed=self.notifications
        self.applyFilter()
        self.refreshControl?.endRefreshing()
        print("Finished")
    }
    task.resume()
}
BOT Axel
  • 470
  • 4
  • 13
  • You are probably calling `.removeLast()` on an empty array. – Eric Aya May 10 '16 at 11:44
  • I forgot to say where it crashed .. My bad .. It crashed here > let jsonDict = try NSJSONSerialization.JSONObjectWithData(data!,options: .AllowFragments) – BOT Axel May 10 '16 at 11:52
  • In this case, read the article I just linked, it explains what happens (your `data` is nil and you're force-unwrapping it). – Eric Aya May 10 '16 at 11:54
  • I don't get it Eric :/ – BOT Axel May 10 '16 at 11:56
  • By using `data!` you are force unwrapping the optional `data`. But this data is nil, so the app crashes. Write a system to ensure the optional `data` is safely unwrapped before using it, with `if let` for example. – Eric Aya May 10 '16 at 11:57
  • But the question is "where `data` is initialized ?" – BOT Axel May 10 '16 at 11:58
  • And why is it working the first time I use it and crash when I'm reusing it ? – BOT Axel May 10 '16 at 11:59
  • `data` comes from `(data, response, error)` which is given to you by `session.dataTaskWithRequest(request)`. This is the network data. If the network request fails, data is nil, and because you're not handling errors and you don't verify that data is not nil before using it, the app crashes. This is what's happening the second time. – Eric Aya May 10 '16 at 12:01
  • But ... I'm verifying the HTTPResponse ... And when I change `data!` to `data` Xcode ask me to place the `!` – BOT Axel May 10 '16 at 12:04
  • Seriously, Axel, learn Swift. Dealing with Optionals is a key concept in this language. I've helped you as much as I can - if you don't understand the basic concepts yet, learn them, I can't do it for you. ;) Here's some reading: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID330 – Eric Aya May 10 '16 at 12:07
  • Also, note that a response of 200 doesn't mean there's data or that the data is valid, it just means that the server is responding. – Eric Aya May 10 '16 at 12:09
  • Okay seems to work now ... Weird ... Thanks you very much ! :) – BOT Axel May 10 '16 at 12:39

0 Answers0