无法使用类型为“的参数列表”调用“jsonObject”(带有:NSData,选项:JSONSerialization.ReadingOptions,错误:inout NSError?)
Posted
技术标签:
【中文标题】无法使用类型为“的参数列表”调用“jsonObject”(带有:NSData,选项:JSONSerialization.ReadingOptions,错误:inout NSError?)【英文标题】:Cannot invoke 'jsonObject' with an argument list of type '(with: NSData, options: JSONSerialization.ReadingOptions, error: inout NSError?) 【发布时间】:2016-12-05 03:47:03 【问题描述】:我是 ios 的新手开发者,仍在学习 youtube 或阅读一些有关 swift 的电子书等。
实际上,我在 youtube iOS Login and Signup Screen Tutorial 上关注了有关如何使用 JSON 数据创建 iOS 登录和注册的本教程,但我认为该代码在带有 xcode 8 的 swift 3 中效果不佳。我有一些问题/错误,我现在不能解决这个问题,我已经google了,但我不知道如何解决这个问题。
这是我的 LoginVC.swift 文件中的屏幕截图
Screenshot of error on my LoginVC.swift
这是 LoginVC.swift 中的所有代码
import UIKit
class LoginVC: UIViewController
@IBOutlet weak var txtUsername: UITextField!
@IBOutlet weak var txtPassword: UITextField!
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view.
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
@IBAction func btnLoginTapped(_ sender: UIButton)
// let userName = txtUsername.text;
// let userPassword = txtPassword.text;
let username = txtUsername.text
let password = txtPassword.text
if ( username!.isEqual("") || password!.isEqual("") )
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Please enter Username and Password"
alertView.delegate = self
alertView.addButton(withTitle: "OK")
alertView.show()
else
var post:NSString = "username=\(username)&password=\(password)" as NSString
NSLog("PostData: %@",post);
var url:NSURL = NSURL(string:"http://192.168.1.17/userAPI/api/users")!
var postData:NSData = post.data(using: String.Encoding.ascii.rawValue)! as NSData
var postLength:NSString = String( postData.length ) as NSString
var request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.httpBody = postData as Data
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: URLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &reponseError)
if ( urlData != nil )
let res = response as! HTTPURLResponse!;
// let dict: [String: Any] = ["key": value]
NSLog("Response code: %ld", res?.statusCode ?? <#default value#>);
if ((res?.statusCode)! >= 200 && (res?.statusCode)! < 300)
var responseData:NSString = NSString(data:urlData! as Data, encoding:String.Encoding.utf8.rawValue)!
NSLog("Response ==> %@", responseData);
var error: NSError?
let jsonData:NSDictionary = JSONSerialization.jsonObject(with: urlData!, options: JSONSerialization.ReadingOptions.mutableContainers, error: &error) as! NSDictionary
// let jsonData:NSDictionary = JSONSerialization.JSONObjectWithData(urlData!, options:JSONSerialization.ReadingOptions.MutableContainers , error: &error) as! NSDictionary
let success:NSInteger = jsonData.value(forKey: "success") as! NSInteger
//[jsonData[@"success"] integerValue];
NSLog("Success: %ld", success);
if(success == 1)
NSLog("Login SUCCESS");
var prefs:UserDefaults = UserDefaults.standard
prefs.set(username, forKey: "USERNAME")
prefs.set(1, forKey: "ISLOGGEDIN")
prefs.synchronize()
self.dismiss(animated: 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 in Failed!"
alertView.message = error_msg as String
alertView.delegate = self
alertView.addButton(withTitle: "OK")
alertView.show()
else
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButton(withTitle: "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.addButton(withTitle: "OK")
alertView.show()
func textFieldShouldReturn(textField: UITextField) -> Bool
//delegate method
textField.resignFirstResponder()
return true
错误实际上在以下几行:
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &reponseError)
NSLog("Response code: %ld", res?.statusCode ?? <#default value#>);
let jsonData:NSDictionary = JSONSerialization.jsonObject(with: urlData!, options: JSONSerialization.ReadingOptions.mutableContainers, error: &error) as! NSDictionary
我有点卡住并困惑如何解决这个问题。
有人来帮忙解决这个问题吗?对此,我真的非常感激。或者有人可以告诉我如何在 Swift3 中使用 API 学习和创建登录屏幕?
谢谢你的帮助,祝大家今天有好事发生!
【问题讨论】:
是的,iOS 在 swift 3 中改变了很多语法。只需检查 XCode 显示错误的方法。 Swift 更改语法。将该方法更改为最新的语法类 func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any @New16 谢谢你这么快回复我,呵呵..是的,错误在截图上,实际上我构建项目后有3个错误。 @GeneCode 好的,先生,我会尝试更改,谢谢您的帮助。 :) 【参考方案1】:这是因为我们在获取数据时没有处理错误。所以我们需要安全地键入种姓数据,然后将其传递给 JsonSerializer。这是代码。
do
let data = try NSData.init(contentsOfFile: path) as Data
let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
print(jsonArray)
catch
【讨论】:
以上是关于无法使用类型为“的参数列表”调用“jsonObject”(带有:NSData,选项:JSONSerialization.ReadingOptions,错误:inout NSError?)的主要内容,如果未能解决你的问题,请参考以下文章
无法使用类型为 (('WeatherResponse?, NSError?) -> Void 的参数列表调用“responseObject”
如何解决错误:无法调用类型为 `......` 的参数列表类型为 `...` 的初始化程序?
无法使用类型为 [重复] 的参数列表调用类型“NSAttributedString”的初始化程序