1
我是Swift上的新成员,但我正在回顾一些例子,例如如何使登录应用程序发送用户名和密码字段到PHP文件并获取json响应。Swift 3 problems解析json响应
当我打印我的responseString我得到:
[{ “用户id”:1, “用户名”: “罗德里戈”, “密码”: “minhoca”, “组名”: “情侣”}]
但是当我尝试解析JSON我从来没有可以设置用户名变量,因为从来没有进入的那部分代码,我只是得到“这里”
感谢您的帮助
func sendLoginInfo(username: String, password: String) -> String{
if let url = URL(string: "myphpurl"){
let request = NSMutableURLRequest(url:url)
request.httpMethod = "POST";// Compose a query string
let postString = "?username=\(myUsername)&password=\(myPassword)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with:request as URLRequest){
data, response, error in
if error != nil{
print("1\(error)")
}
else{
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("response string = \(responseString!)")
}
do {
if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
// Print out dictionary
print(convertedJsonIntoDict)
// Get value by key
let firstNameValue = convertedJsonIntoDict["username"] as? String
print("here = \(firstNameValue!)")
}
else{
print("here")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
task.resume()
}
return ""
}
谢谢,但现在它给了我: 使用未申报类型的NSDictionary –
对不起我的代码做了一个错字。再次尝试此代码我已编辑它。我拼写关键字它是NSDictionary –
非常感谢,这工作得很好。 –