[英]Swift : fatal error: unexpectedly found nil while unwrapping an Optional value
I am trying to access REST web service, but its giving this - fatal error: unexpectedly found nil while unwrapping an Optional value. 我正在尝试访问REST Web服务,但它给出了-致命错误:在展开Optional值时意外发现nil。
Below is the code - So i have this RESTParser class - 下面是代码-所以我有这个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){
}
}
Error is @ this line - self.delegate?.getReceiveData(receiveData, sender: self) in connectionDidFinishLoading function. 错误是@这行-connectionDidFinishLoading函数中的self.delegate?.getReceiveData(receiveData,sender:self)。
And calling this from my project details view controller - but as soon as getReceiveData method is called this fatal error is coming. 并从我的项目详细信息视图控制器中调用此方法-但是一旦调用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){
}
}
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.