调用中的额外参数 'error'
Extra argument 'error' in call
我遇到了这个错误Extra argument 'error' in call
上下文中的代码
var post:NSString = "name=\(Username)&email=\(Email)&phone=\(phonenumb)&password=\(Password)&address=\(address)"
NSLog("PostData: %@",post);
var url:NSURL = NSURL(string: "http://userregistration.php")!
var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String( postData.length )
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
var error: NSError?
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
//[jsonData[@"success"] integerValue];
NSLog("Success: %ld", success);
if(success == 1)
{
NSLog("Sign Up SUCCESS");
self.dismissViewControllerAnimated(true, completion: nil)
} else {
var error_msg:NSString
if jsonData["error_message"] as? NSString != nil {
error_msg = jsonData["error_message"] as! NSString
} else {
error_msg = "Unknown Error"
}
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign Up Failed!"
alertView.message = error_msg as String
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign Up Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failure"
if let error = reponseError {
alertView.message = (error.localizedDescription)
}
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
我的错误出现在两个地方。
The first one
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
The second one
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
我试过以下方法
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
但是我的结果报错如下
used unresolved jsonData
现在有人可以帮助我如何将这个 do catch 添加到我上面的原始代码中以纠正错误。
改变
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
与
let urlData = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
并改变
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
与
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: []) as! NSDictionary
你的完整代码将是:
let url:NSURL = NSURL(string: "http://userregistration.php")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let reponseError: NSError?
var response: NSURLResponse?
do {
let urlData = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: []) as! NSDictionary
let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
//[jsonData[@"success"] integerValue];
NSLog("Success: %ld", success);
if(success == 1)
{
NSLog("Sign Up SUCCESS");
self.dismissViewControllerAnimated(true, completion: nil)
} else {
var error_msg:NSString
if jsonData["error_message"] as? NSString != nil {
error_msg = jsonData["error_message"] as! NSString
} else {
error_msg = "Unknown Error"
}
let alertView:UIAlertView = UIAlertView()
alertView.title = "Sign Up Failed!"
alertView.message = error_msg as String
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} catch let error as NSError {
print("json error: \(error.localizedDescription)")
}
} else {
let alertView:UIAlertView = UIAlertView()
alertView.title = "Sign Up Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
}
就目前而言,您应该知道 NSURLConnection
已被弃用。请使用 NSURLSession
来支持 iOS 的新版本。这是它的代码:
func postRequestWithFormData(strUrl: String, param: NSDictionary?, completionHandler: (responseData: NSDictionary?, error: NSError?) -> ()) -> (){
if isConnectedToNetwork(){
let url = NSURL(string: strUrl)!
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
var paramString = String()
for (key, value) in param! {
paramString = paramString + (key as! String) + "=" + (value as! String) + "&"
}
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request) {data, response, error -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
do{
if data != nil{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
if let parseJSON = json {
// Parsed JSON
completionHandler(responseData: parseJSON, error: nil)
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
#if DEBUG
print("Error could not parse JSON: \(jsonStr)")
#endif
}
}else{
completionHandler(responseData: nil, error: error)
}
}catch let error as NSError{
print(error.localizedDescription)
completionHandler(responseData: nil, error: error)
}
})
}
task.resume()
}else{
//Alert No Internet Connection
}
}
如果您仍然遇到任何错误,请告诉我。
Usage
postRequestWithFormData(appConstants.BASEURL + appConstants.API_USER_SIGN_IN, param: paramaters) { (responseData, error) in
if responseData != nil && error == nil{
if responseData!.valueForKey("response_status") as! String == "0"{
helperInstance.showSingleAlert(responseData!.valueForKey("message") as! String)
}else if responseData!.valueForKey("response_status") as! String == "1"{
//Getting Data
}
}else if error != nil{
//Error Received
}
}
我遇到了这个错误Extra argument 'error' in call
上下文中的代码
var post:NSString = "name=\(Username)&email=\(Email)&phone=\(phonenumb)&password=\(Password)&address=\(address)"
NSLog("PostData: %@",post);
var url:NSURL = NSURL(string: "http://userregistration.php")!
var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String( postData.length )
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
var error: NSError?
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
//[jsonData[@"success"] integerValue];
NSLog("Success: %ld", success);
if(success == 1)
{
NSLog("Sign Up SUCCESS");
self.dismissViewControllerAnimated(true, completion: nil)
} else {
var error_msg:NSString
if jsonData["error_message"] as? NSString != nil {
error_msg = jsonData["error_message"] as! NSString
} else {
error_msg = "Unknown Error"
}
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign Up Failed!"
alertView.message = error_msg as String
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign Up Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failure"
if let error = reponseError {
alertView.message = (error.localizedDescription)
}
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
我的错误出现在两个地方。
The first one
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
The second one
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
我试过以下方法
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
但是我的结果报错如下
used unresolved
jsonData
现在有人可以帮助我如何将这个 do catch 添加到我上面的原始代码中以纠正错误。
改变
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
与
let urlData = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
并改变
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
与
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: []) as! NSDictionary
你的完整代码将是:
let url:NSURL = NSURL(string: "http://userregistration.php")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let reponseError: NSError?
var response: NSURLResponse?
do {
let urlData = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: []) as! NSDictionary
let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
//[jsonData[@"success"] integerValue];
NSLog("Success: %ld", success);
if(success == 1)
{
NSLog("Sign Up SUCCESS");
self.dismissViewControllerAnimated(true, completion: nil)
} else {
var error_msg:NSString
if jsonData["error_message"] as? NSString != nil {
error_msg = jsonData["error_message"] as! NSString
} else {
error_msg = "Unknown Error"
}
let alertView:UIAlertView = UIAlertView()
alertView.title = "Sign Up Failed!"
alertView.message = error_msg as String
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} catch let error as NSError {
print("json error: \(error.localizedDescription)")
}
} else {
let alertView:UIAlertView = UIAlertView()
alertView.title = "Sign Up Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
}
就目前而言,您应该知道 NSURLConnection
已被弃用。请使用 NSURLSession
来支持 iOS 的新版本。这是它的代码:
func postRequestWithFormData(strUrl: String, param: NSDictionary?, completionHandler: (responseData: NSDictionary?, error: NSError?) -> ()) -> (){
if isConnectedToNetwork(){
let url = NSURL(string: strUrl)!
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
var paramString = String()
for (key, value) in param! {
paramString = paramString + (key as! String) + "=" + (value as! String) + "&"
}
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request) {data, response, error -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
do{
if data != nil{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
if let parseJSON = json {
// Parsed JSON
completionHandler(responseData: parseJSON, error: nil)
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
#if DEBUG
print("Error could not parse JSON: \(jsonStr)")
#endif
}
}else{
completionHandler(responseData: nil, error: error)
}
}catch let error as NSError{
print(error.localizedDescription)
completionHandler(responseData: nil, error: error)
}
})
}
task.resume()
}else{
//Alert No Internet Connection
}
}
如果您仍然遇到任何错误,请告诉我。
Usage
postRequestWithFormData(appConstants.BASEURL + appConstants.API_USER_SIGN_IN, param: paramaters) { (responseData, error) in
if responseData != nil && error == nil{
if responseData!.valueForKey("response_status") as! String == "0"{
helperInstance.showSingleAlert(responseData!.valueForKey("message") as! String)
}else if responseData!.valueForKey("response_status") as! String == "1"{
//Getting Data
}
}else if error != nil{
//Error Received
}
}