【发布时间】:2015-01-21 12:34:36
【问题描述】:
我正在尝试学习 Swift 和 IOS 开发。现在,我已经在一个简单的测验应用程序上苦苦挣扎了几天。我已经让应用程序正常工作,我什至设法将它连接到数据库。现在的问题是,使用 JSON 解析我可以很好地解析数据库中的文本,直到我用普通文本和字符替换我的虚拟文本。解析脚本如下所示:
let urlPath = "xxxx/json.php"
let url: NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
var questionNummer = 0
// let sporsmalArray=[question]()
typealias questionArray = [AnyObject] // or whatever is inside, maybe String
println("starting web request")
let task = session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
println("passed web request")
if (error != nil) {
// If there is an error in the web request, print it to the console
println("WebError: " + error.localizedDescription)
}else {
println("no web request error")
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if err != nil {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
else {
println("no json error")
let questions=jsonResult["data"] as? [[String:String]]
if(questions == nil){println("questions is nil")}
if (questions != nil) {
for question in questions! {
println("for: question")
questionNummer += 1
let answer1=question["answerOne"]!
let answer2=question["answerTwo"]!
let answer3=question["answerThree"]!
let answer4=question["answerFour"]!
let aidd=question["id"]!
let questionItself=question["questionTemplate"] as String!
let correctAnswerJson=question["correctAnswer"]
println("question parsed")
var newQuestion = [questionItself , answer1 , answer2 , answer3 , answer4, correctAnswerJson]
var questionArray = Array<myspecialarray>();
questionArray.append(newQuestion)
if(questionArray.isEmpty) {println("questionArray is null")}
else{println("questionArray is not null")}
self.sporsmalArray.append(questionArray)
println("Neste printer sporsmal arrayen:")
println(self.sporsmalArray)
println("Arrayen er ferdig")
//Jeg kaller på intial state her for å få med verdiene i arrayen
self.initialState()
}
}else{
println("Kjører ikke")}
}
}
})
task.resume()
如果数据库包含æøå,则脚本不会向我的数组添加任何内容。我的打印行显示脚本有效,但是当我打印数组时它是空的。
starting web request
Dette teller påå spørsmålsarrayen: 0
passed web request
no web request error
no json error
questions is nil
当我从数据库中删除北欧字母时,脚本又可以正常工作了。
starting web request
Dette teller påå spørsmålsarrayen: 0
passed web request
no web request error
no json error
for: question
question parsed
questionArray is not null
Neste printer sporsmal arrayen:
[(
(
"Dettekommerfrainternet ! ",
as1nett,
aa2nett,
aa3nett,
aa4nett,
4
)
)]
数据库字符集设置为 varchar 和瑞典语 utf-8。
这个问题可能是什么?
【问题讨论】:
-
您应该将您的国际字符放回数据库中,然后检查生成的 JSON。如果没有看到实际显示问题的实际 JSON 或测试 URL,很难说问题出在哪里。我怀疑是服务器问题,但这里不足以诊断问题。
-
是的,当然,我已经把它们放回去了。谢谢你的时间。 :)
-
当我在浏览器中进入 URL 时,它也为零。所以我认为你对服务器问题是正确的。知道问题可能是什么吗?
-
我修好了!通过把 mysqli_set_charset($con, "utf8");在我的 php 脚本中连接之后。
标签: json database parsing swift