在iPhone上测试时应用程序崩溃,但在模拟器中没有

时间:2018-01-24 15:16:52

标签: ios json iphone swift twitter

我有一个代码从twitter获取JSON并将其放入名为feedStruct的结构中,但也将其解析为UITableViewController。

我已经在模拟器中多次测试了它,但也想在我的iPhone上测试它,然后它在这段代码中崩溃了。我在“使应用程序崩溃”的行旁边发表了评论:

  

线程8:致命错误:在解包可选值时意外发现nil

(我认为在某些时候,线程6也认为,如果这与它有任何关系。)

以下是代码:

import Foundation

protocol twitterModelProtocol: class {
    func twitterDownloaded(items: [Any])
    func feedTwitterDatesDownloaded(items: [feedStruct])
}

class twitterModel: NSObject {

    //properties
    weak var delegate: twitterModelProtocol!

    let urlPath = "http://MYWEBPAGE/twit.php" //this will be changed to the path where service.php lives

    func downloadTwitterItems() {
        let url: URL = URL(string: urlPath)!
        let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
        let task = defaultSession.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print("Failed to download twitter data")
            } else {
                print("Twitter data downloaded")
                self.parseTwitterJSON(data!)
            }
        }    
        task.resume()
    }

    func parseTwitterJSON(_ data:Data) {
        var jsonResult = [Any]()

        do{
            jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! [Any]
        } catch let error as NSError {
            print(error)
        }

        var jsonElement = NSDictionary()
        var feeds = [feedStruct]()

        for i in 0 ..< jsonResult.count {
            jsonElement = jsonResult[i] as! NSDictionary

            let feed = feedStruct()
            //the following insures none of the JsonElement values are nil through optional binding
            if let unixstamp = jsonElement["created_at"] as? String {

                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy"

                print(unixstamp)

                let date = dateFormatter.date(from: unixstamp)! //THIS LINE IS MAKING THE APP CRASH ON iPHONE NOT SIMULATOR <<<<<<<<<<<<<<<<<<<<<
                let calendar = Calendar.current
                let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
                let finalDate = calendar.date(from:components)

                let timestamp = finalDate?.timeIntervalSince1970
                let finalTimestamp = String(format: "%.0f", timestamp!)

                feed.date = finalTimestamp
                feed.type = "twitter"   
            }
            feeds.append(feed)   
        }

        DispatchQueue.main.async(execute: { () -> Void in
            self.delegate.twitterDownloaded(items: jsonResult)
            self.delegate.feedTwitterDatesDownloaded(items: feeds)  
        })
    }

}

1 个答案:

答案 0 :(得分:1)

尝试设置以下内容(设备的日期/时间设置可能会导致模拟器和设备之间出现差异):

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy"
dateFormatter.timeZone = TimeZone(identifier: "GMT")
dateFormatter.locale = Locale(identifier: "en_US_POSIX")

guard let date = dateFormatter.date(from: unixstamp) else {
    // deal with non-existent date
}