我收到此错误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()
}
我的错误发生在2个地方。
第一个
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
第二个
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)
}
但我导致如下错误
使用未解析的
jsonData
现在任何人都可以帮助我如何添加这个抓住我的上述原始代码以纠正错误。
答案 0 :(得分:1)
至于,您应该知道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
}
}
如果您仍然遇到任何错误,请与我们联系。
用法
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
}
}
答案 1 :(得分:0)
更改
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()
}
}
}