0
votes

I am trying to access REST web service, but its giving this - fatal error: unexpectedly found nil while unwrapping an Optional value.

Below is the code - So i have this RESTParser class -

protocol RESTParserDelegate
{
    func getReceiveData(data:NSMutableData,sender:RESTParser)
}

class RESTParser: NSObject, NSURLConnectionDataDelegate 
{

var receiveData: NSMutableData!
var requestConnection: NSURLConnection!
var delegate: RESTParserDelegate?

func receiveData(resData:NSMutableData){
    receiveData = resData
}

func requestConnection(reqConn:NSURLConnection){
    requestConnection = reqConn
}

func httpRequest(myRequest:NSMutableURLRequest){
    self.requestConnection = NSURLConnection(request: myRequest, delegate: self)

}
// NSURLConnectionDataDelegate methods

func connection(connection: NSURLConnection, didReceiveData data: NSData){
    self.receiveData?.appendData(data)
}

func connectionDidFinishLoading(connection: NSURLConnection){
    self.delegate?.getReceiveData(receiveData, sender: self) // error @ this line
    self.delegate = nil
    self.receiveData = nil
    self.requestConnection = nil
}
func connection(connection: NSURLConnection, didFailWithError error: NSError){
    NSLog("Failed with error - %@ ",error.localizedDescription)

}
func parseData(data:NSMutableData){
}
}

Error is @ this line - self.delegate?.getReceiveData(receiveData, sender: self) in connectionDidFinishLoading function.

And calling this from my project details view controller - but as soon as getReceiveData method is called this fatal error is coming.

class ProjectDetails_tab: UIViewController, RESTParserDelegate{

override func viewDidLoad() {
    super.viewDidLoad();
    //var projectData: NSDictionary = [String:String]()

    var url:String = "http://domianName.com"

    var nsURL = NSURL(string: url)
    var createrequest: NSMutableURLRequest = NSMutableURLRequest(URL: nsURL!)

    createrequest.HTTPMethod = "GET"

    var rest = RESTParser()
    rest.delegate=self
    rest.httpRequest(createrequest)

}

func getReceiveData(data:NSMutableData,sender:RESTParser){   
}    
}
1
on which line you get this error...put some breakpoint and check...EI Captain v2.0
Error is @ this line - self.delegate?.getReceiveData(receiveData, sender: self) in connectionDidFinishLoading function.RichieRich

1 Answers

0
votes

Not clear that fatal error with which line of your code. But you can recheck your delegate object or:

// NSURLConnectionDataDelegate methods
func connection(didReceiveResponse: NSURLConnection, didReceiveResponse response: NSURLResponse) {
    // Recieved a new request, clear out the data object
    self.receiveData = NSMutableData()
}

func connection(connection: NSURLConnection, didReceiveData data: NSData){
    self.receiveData?.appendData(data)
}

func connectionDidFinishLoading(connection: NSURLConnection!) {
    // Request complete, self.data should now hold the resulting info
}