【问题标题】:Extra argument 'error' in call调用中的额外参数“错误”
【发布时间】:2016-08-09 06:19:43
【问题描述】:

我收到此错误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()
   }

我的错误发生在两个地方。

第一个

  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

现在任何人都可以帮助我如何在上面的原始代码中添加这个 do catch 来纠正错误。

【问题讨论】:

    标签: ios json swift nserror do-catch


    【解决方案1】:

    改变

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

    【讨论】:

      【解决方案2】:

      就您而言,您应该知道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
                  }
              }
      

      【讨论】:

      • 如何在我的按钮操作 clikc 上调用此函数
      猜你喜欢
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 2018-01-02
      相关资源
      最近更新 更多