应用程序在iPhone 6上崩溃,但在iPhone 6模拟器上运行

时间:2017-04-02 23:10:14

标签: ios swift xcode ios-simulator iphone-6

我不明白为什么我的应用程序在模拟器上工作得很好,而是当我在iPhone崩溃时运行。可能是什么?

enter image description here

import UIKit
import CoreData



class HomeTableViewController: UITableViewController{

    var arrayEntity : [Questions] = []

    override func viewDidLoad(){
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        if (CoreDataController.shared.checkIfIsEmpty() == true) { getJSON() }
        else { arrayEntity = CoreDataController.shared.loadQuestion()!
        //reload della tableview quando l'array si modifica
        self.tableView.reloadData()
        }
    }

    struct ProvaREST{

        var userId: Int = 0
        var id: Int = 0
        var title: String = ""
        var body: String = ""

        static func parsereviewJSONData(data: Data) -> [ProvaREST] {

            var provaREST = [ProvaREST]()

            do {
                let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)

                // Parse JSON data
                if let reviews = jsonResult as? [Dictionary<String, Any>] {
                    for review in reviews {

                        var newReview = ProvaREST()

                        newReview.userId = review["userId"] as! Int
                        newReview.id = review["id"] as! Int
                        newReview.title = review["title"] as! String
                        newReview.body = review["body"] as! String

                        provaREST.append(newReview)
                    }

                }
            } catch let err {
                print(err)
            }

            return provaREST
        }

    }


    func getJSON(){

        var reviews = [ProvaREST]()

        let sessionConfig = URLSessionConfiguration.default

        let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
        guard let URL = URL(string: "https://jsonplaceholder.typicode.com/posts") else { return }
        var request = URLRequest(url: URL)
        request.httpMethod = "GET"

        let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
            if (error == nil) {
                // Parse JSON Data
                if let data = data {
                    reviews = ProvaREST.parsereviewJSONData(data: data)


                    //Core data saving

                    for i in 0 ..< reviews.count{
                        CoreDataController.shared.addQuestion(userID: reviews[i].userId, id: reviews[i].id, title: reviews[i].title, body: reviews[i].body)
                    }

                    //quando finisco di aggiungere, tengo in memoria (per zone fuori copertura) ed estraggo i dati per la tableview
                    self.arrayEntity = CoreDataController.shared.loadQuestion()!
                    self.tableView.reloadData()

                }
            } else {
                // Failure connection
                print("Nessuna connessione")

            }
        })
        task.resume()
        session.finishTasksAndInvalidate()
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrayEntity.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        cell.textLabel?.text = arrayEntity[indexPath.row].body
        cell.detailTextLabel?.text = String(arrayEntity[indexPath.row].id)

        return cell
    }

}

import Foundation
import UIKit
import CoreData

class CoreDataController {

    static let shared = CoreDataController()

    private var context: NSManagedObjectContext

    private init() {
        let application = UIApplication.shared.delegate as! AppDelegate
        self.context = application.persistentContainer.viewContext
    }

    func addQuestion(userID: Int, id: Int, title: String, body: String) {
        let entity = NSEntityDescription.entity(forEntityName: "Questions", in: self.context)

        let newQuestion = Questions(entity: entity!, insertInto: self.context)
        newQuestion.userid = Int32(userID)
        newQuestion.id = Int32(id)
        newQuestion.title = title
        newQuestion.body = body

        do {
            try self.context.save()
        } catch{
            print("Errore")
        }
    }

    func loadQuestion() -> [Questions]? {

        print("Recupero libri:")

        let fetchRequest: NSFetchRequest<Questions> = Questions.fetchRequest()

        do {
            let array = try self.context.fetch(fetchRequest) as [Questions]

            guard array.count > 0 else {print("[EHY!] Non ci sono elementi da leggere "); return array}
            return array

        }catch let err{

            print(err)
            return nil
        }
    }


    func checkIfIsEmpty() -> Bool{

        let fetchRequest: NSFetchRequest<Questions> = Questions.fetchRequest()

        do {
            let array = try self.context.fetch(fetchRequest)
            guard array.count > 0 else { return true }
            return false

        }catch{
            print("Errore nella fetchRequest")
            return false
        }
    }

}

coredatacontroller类是处理数据库操作的类coredatacontroller类是处理数据库操作的类coredatacontroller类是处理数据库操作的类

0 个答案:

没有答案