我正在尝试验证我的应用收据,并且已成功完成了我在网上找到的一些代码。但是,我正在模拟用户在尝试验证收据时未连接到互联网的事件,并且在执行此操作时遇到崩溃。仅当我的设备未连接到互联网时,以下do / catch方法才会导致anyObj
行崩溃:
func validateRecipt(){ var response:NSURLResponse? var error:NSError?
var receipt: NSData = NSData()
if let url = NSBundle.mainBundle().appStoreReceiptURL {
if let appReceipt = NSData(contentsOfURL: url) {
print("Receipt Found")
receipt = appReceipt
}else {
print("Receipt not Found")
}
}else {
print("Could not load Receipt")
}
//https://buy.itunes.apple.com/verifyReceipt
let request = NSMutableURLRequest(URL: NSURL(string: "https://sandbox.itunes.apple.com/verifyReceipt")!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let receiptdata:NSString = receipt.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithLineFeed)
//NSLog("%@",receiptdata)
let payload:NSString = "{\"receipt-data\" : \"\(receiptdata)\"}"
let payloadData = payload.dataUsingEncoding(NSUTF8StringEncoding)
let err: NSError?
request.HTTPBody = payloadData
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var err: NSError?
//let json = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
var json: AnyObject?
do {
let anyObj = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]
****//App Crashes Here ^^//****
json = anyObj
} catch {
print("Fetch failed: \((error as NSError).localizedDescription)")
}
if(err != nil) {
print(err!.localizedDescription)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
else {
if let parseJSON = json {
print("Recipt \(parseJSON)")
print(parseJSON.count)
}
else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Recipt Error: \(jsonStr)")
}
print("You gets nathan")
}
})
task.resume()
}
崩溃只是fatal error: unexpectedly found nil while unwrapping an optional value
我无法理解do / catch方法,所以我不相信我完全理解这里发生了什么。所以我猜我的问题是当anyObj返回nil时如何避免这种崩溃?
答案 0 :(得分:2)
我猜测调试器光标指向的行是:
let anyObj = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]
...并且您的data
变量为nil(即,optional不包含任何值)。在强制解包前(!
运算符)检查它。
((error as NSError).localizedDescription
不能,因为catch
块内的错误应该是非零的,而NSError
的情况不合适会产生不同的错误消息,我想)。
这是你安全打开的方式:
if let safeData = data { // <-- YOU NEED TO DO THIS
// data is 'NSData?', safeData is 'NSData'.
// If data contained any value, it is now assigned to safeData.
// Use safeData as the source of your JSON (**not** data).
}
else{
print("error: data is nil!")
}