gpt4 book ai didi

ios - NSURLConnection中建立错误案例,Swift中JSON解析

转载 作者:行者123 更新时间:2023-11-28 07:14:39 25 4
gpt4 key购买 nike

我正在尝试从我网站上的 JSON 中提取信息。这样做时,如果连接出现错误,它应该返回该错误并将其记录到控制台。我遇到的问题是,如果我打开飞机更多或以其他方式丢失信号,错误: fatal error :在展开可选值时意外发现 nil 会使应用程序崩溃。当我设置了简单地记录错误的条件时,为什么它会返回这个?提前致谢!

我不确定为什么没有记录错误并防止应用程序崩溃。任何指示都会有所帮助。

JSONLoader.swift

import Foundation

var arrayOfMeals: [Meal] = [Meal]()
var weekDayArray = ["monday"]


func getJSON(urlToRequest: String) -> NSDictionary {

var url: NSURL = NSURL(string: urlToRequest)!
var jsonRequest: NSURLRequest = NSURLRequest(URL: url)
var jsonResponse: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil

var error: NSError?
var dataValue: NSData = NSURLConnection.sendSynchronousRequest(jsonRequest, returningResponse: jsonResponse, error:&error)!

if error? == nil {
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataValue, options: NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
if error? == nil {
return jsonResult
}
else {
return NSDictionary(object: "Error: Something with parsing went wrong :(", forKey: "error")
}
}
else {
return NSDictionary(object: "Error: There was an error with your connection :(", forKey: "error")
}

}

func loadJSON(jsonDictionary: NSDictionary) {

for days in weekDayArray{
var resultsArray = jsonDictionary[days] as NSArray
for obj: AnyObject in resultsArray{
let breakfast = (obj.objectForKey("breakfast")! as String)
let lunch = (obj.objectForKey("lunch")! as String)
let dinner = obj.objectForKey("dinner")! as String
let dateString = obj.objectForKey("dateString")! as String
let dayOfWeek = obj.objectForKey("dayOfWeek")! as String
let newMeal = Meal(breakfast: breakfast, lunch: lunch, dinner: dinner, dayOfWeek: dayOfWeek, dateString: dateString)
if theDays(newMeal.dateString) >= 0 {
arrayOfMeals.append(newMeal)
}
}
}


}

我希望函数 getJSON 建立一个到站点的 NSURLConnection,解析 JSON 日期,并返回一个 NSDictionary。如果连接中存在错误,则会建立一个错误案例,然后它会返回一个字典,其中包含一个解释错误的值。解析 JSON 文件时发生额外的错误情况,并返回具有类似错误的 NSDictionary。

我希望函数 loadJSON 创建对象 Meal 的实例,我将其定义为具有早餐、午餐、晚餐、日期和星期几的属性。此实例的值是函数 getJSON 返回的 NSDictionary 的结果。如果这一天是 future 的一天,请将其附加到我的 arrayOfMeals 中。否则,忽略该实例。

餐 View Controller

override func viewDidLoad() {
super.viewDidLoad()

var req = getJSON("http://www.seandeaton.com/meals/Mealx")
loadJSON(req)


}

MealModel.swift - 创建膳食实例

class Meal {

let breakfast: String
let lunch: String
let dinner: String
let dayOfWeek: String
let dateString: String

init(breakfast: String, lunch: String, dinner: String, dayOfWeek: String, dateString: String) {

self.breakfast = breakfast
self.lunch = lunch
self.dinner = dinner
self.dayOfWeek = dayOfWeek
self.dateString = dateString

}

}

如何防止应用程序在无法建立连接时崩溃并将错误消息记录到控制台?再次感谢。

最佳答案

关键观察是在对 sendSynchronousRequest 的调用中您在其中检索 NSData , 你已经定义了 NSData不是可选的,你附加了一个 !这将强制解包可选的返回值。因此,如果可选 NSDatanil (如果有任何网络问题就会发生),此代码将失败。

相反,您应该只保留 NSData作为可选(即 NSData? )并检查它是否是 nil或者在尝试打开它之前不这样做。因此,我可能会建议如下:

func retrieveJSON(urlToRequest: String) -> NSDictionary {

let url: NSURL = NSURL(string: urlToRequest)!
let jsonRequest: NSURLRequest = NSURLRequest(URL: url)

var jsonResponse: NSURLResponse?
var error: NSError?
let dataValue = NSURLConnection.sendSynchronousRequest(jsonRequest, returningResponse: &jsonResponse, error:&error)

if dataValue != nil {
if let jsonResult = NSJSONSerialization.JSONObjectWithData(dataValue!, options: .MutableContainers, error: &error) as? NSDictionary {
return jsonResult
} else {
return [
"error": "Error: Something with parsing went wrong :(",
"localizedDescription": error?.localizedDescription ?? ""
];
}
}
else {
return [
"error": "Error: There was an error with your connection :(",
"localizedDescription": error?.localizedDescription ?? ""
];
}
}

以上内容将修复由于强制解包可选的 NSData 而导致的崩溃。 , 应该是 nil如果有网络问题。请注意,您没有向我们展示调用 getJSON 的代码然后随后调用 loadJSON ,但我假设您正在对那里的错误处理进行必要的检查。

请注意,我还取消了尴尬 AutoreleasingUnsafeMutablePointer<NSURLResponse?>构造。我还添加了 localizedDescription返回字典的错误。

就个人而言,我通常会返回完整的 NSError对象和 NSURLResponse对象,以便调用者可以诊断错误的确切性质,而不仅仅是文本描述。


在对您的代码进行更彻底的修改时,我建议您通常避免同步请求。永远不要从主线程执行同步请求。

例如,您可以定义异步执行请求的方法,如下所示:

func retrieveJSON(urlToRequest: String, completionHandler:(responseObject: NSDictionary?, error: NSError?) -> ()) {

let url: NSURL = NSURL(string: urlToRequest)!
let jsonRequest: NSURLRequest = NSURLRequest(URL: url)

var jsonResponse: NSURLResponse?
NSURLConnection.sendAsynchronousRequest(jsonRequest, queue: NSOperationQueue.mainQueue()) {
response, data, error in

if data == nil {
completionHandler(responseObject: nil, error: error)
} else {
var parseError: NSError?
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &parseError) as NSDictionary?
completionHandler(responseObject: jsonResult, error: error)
}
}
}

然后您可以使用“尾随闭包语法”调用它,如下所示:

retrieveJSON(urlString) {
responseObject, error in

if responseObject == nil {
// handle error here, e.g.

println(error)
return
}

// handle successful the `NSDictionary` object, `responseObject`, here
}

// but don't try to use the object here, because the above runs asynchronously

关于ios - NSURLConnection中建立错误案例,Swift中JSON解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26818145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com