http://beta.json-generator.com/api/json/get/E1jKVbplX我已成功注册。我对身份验证很感兴趣。我访问了所有数据。但我在访问个人用户数据时遇到了困难。请看下面的代码并纠正我。 var email =“bhupal” var pwd =“k”
//
let parameters: Dictionary<String, AnyObject> = ["Email": email as AnyObject, "Password": pwd as AnyObject,"Type" : "Organization" as AnyObject,"Mode" : "Register" as AnyObject]
//create the url with URL
let url = URL(string: "http://beta.json-generator.com/api/json/get/E1jKVbplX ")! //change the url
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "GET" //set http method as GET
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil
{
print ("ERROR")
}
else
{
if let content = data
{
do
{
//Array
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(myJson)
print("--------")
print(myJson[0])
print(myJson[1])
print("--------")
email = myJson["Email"] as? String
pwd = myJson["Password"] as? String
print("--------")
print(email)
print(pwd)
print("--------")
}
catch
{
}
}
}
}
task.resume()
答案 0 :(得分:0)
您的回复是词典数组,因此myJson[0]
会返回一个字典对象,您应该尝试访问Email
或Password
的值。
您可以尝试以下代码来访问电子邮件和密码:
for dict in myJson { // myJson is array and dict will of dictionary object
let email = dict[Email]
let password = dict[Password]
print("--------")
print("Email is : \(email)")
print("Password is : \(password)")
print("--------")
}
注意:您需要即兴创作。