Swift:致命错误:在展开Optional值时意外发现nil

时间:2015-05-15 12:31:54

标签: ios web-services swift rest

我正在尝试访问REST Web服务,但它给出了这个 - 致命错误:在解开Optional值时意外地发现了nil。

下面是代码 - 所以我有这个RESTParser类 -

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){
}
}

错误是@ this line - 在connectionDidFinishLoading函数中的self.delegate?.getReceiveData(receiveData,sender:self)。

从我的项目详细信息视图控制器中调用它 - 但是一旦调用了getReceiveData方法,就会发生致命错误。

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 个答案:

答案 0 :(得分:0)

不清楚您的代码行的致命错误。但您可以重新检查您的委托对象或:

// 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
}