从本地化字符串

时间:2017-01-27 19:37:46

标签: ios core-data webkit

编辑:代码现在正在运行,结果证明它是过时的数据。我保存并清理了项目,重置模拟器,现在它正在工作!谢谢@pbasdf帮助我!

我仍然习惯于核心数据和本地化字符串,所以我不确定我是否错误地使用了本地化字符串,或者问题是否在其他地方,但是当我点击我可以看到的单元格时我的print语句,所有值都是nil,显然没有加载网页。

我正在使用localized.strings文件将名称等同于其对应的URL:

"iPhone" = "http://www.apple.com/iphone/";
"iPad" = "http://www.apple.com/ipad/";
"Macbook" = "http://www.apple.com/macbook/";
"Google" = "https://www.google.com/";
"Firebase" = "https://firebase.google.com/";
"Magic Leap" = "https://www.magicleap.com/";
"Facebook" = "https://www.facebook.com/";
"Instagram" = "https://www.instagram.com/?hl=en";
"WhatsApp" = "https://www.whatsapp.com/";
"Model S" = "https://www.tesla.com/models";
"Model X" = "https://www.tesla.com/modelx";
"Powerwall" = "https://www.tesla.com/powerwall";
"Twitter" = "https://twitter.com/?lang=en";
"Periscope" = "https://www.periscope.tv/";
"Vine" = "https://vine.co/";

因此,我可以设置url实体的String属性(类型Product)。公司和产品词典:

let defaultProducts = ["Apple" : ["iPhone", "iPad", "Macbook"],
                               "Google" : ["Google", "Firebase", "Magic Leap"],
                               "Facebook" : ["Facebook", "Instagram", "WhatsApp"],
                               "Tesla" : ["Model S", "Model X", "Powerwall"],
                               "Twitter" : ["Twitter", "Periscope", "Vine"]]

这是我职能部门的相关代码:

let companyProducts = defaultProducts[name]

for productName in companyProducts! {

    let product = NSManagedObject(entity: productEntity, insertInto:managedContext)
    let names = NSLocalizedString(productName, comment:"")

    product.setValue(productName, forKey: "name")
    product.setValue(productName, forKey: "image")
    product.setValue(names, forKey: "url")

    product.setValue(company, forKey: "company")
}

然后我用它来点击单元格时显示网页

// WebView
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    let managedContext =
        appDelegate.persistentContainer.viewContext

    let entity =
        NSEntityDescription.entity(forEntityName: "Product",
                                   in: managedContext)!

    let product = NSManagedObject(entity: entity,
                                  insertInto: managedContext)

    if let url = product.value(forKey: "url") as? URL {
        webView.load(URLRequest(url: url))
        webView.allowsBackForwardNavigationGestures = true
        view = webView

    }
    print(product.value(forKey: "url") as? URL)
}

我在localized.strings中做错了什么,导致nil值?

使用网址词典编辑:setDefaults()

func setDefaults() {
    let userDefaults = UserDefaults.standard
    let defaultValues = ["firstRun" : true]
    userDefaults.register(defaults: defaultValues)

    if userDefaults.bool(forKey: "firstRun") {
        let defaultProducts = ["Apple" : ["iPhone", "iPad", "Macbook"],
                               "Google" : ["Google", "Firebase", "Magic Leap"],
                               "Facebook" : ["Facebook", "Instagram", "WhatsApp"],
                               "Tesla" : ["Model S", "Model X", "Powerwall"],
                               "Twitter" : ["Twitter", "Periscope", "Vine"]]

        let urlDictionary = ["iPhone" : "http://www.apple.com/iphone/",
                           "iPad" : "http://www.apple.com/ipad/",
                           "Macbook" : "http://www.apple.com/macbook/",
                           "Google" : "https://www.google.com/",
                           "Firebase" : "https://firebase.google.com/",
                           "Magic Leap" : "https://www.magicleap.com/",
                           "Facebook" : "https://www.facebook.com/",
                           "Instagram" : "https://www.instagram.com/?hl=en",
                           "WhatsApp" : "https://www.whatsapp.com/",
                           "Model S" : "https://www.tesla.com/models",
                           "Model X" : "https://www.tesla.com/modelx",
                           "Powerwall" : "https://www.tesla.com/powerwall",
                           "Twitter" : "https://twitter.com/?lang=en",
                           "Periscope" : "https://www.periscope.tv/",
                           "Vine" : "https://vine.co/"]

        let companyEntity = NSEntityDescription.entity(forEntityName: "Company", in: managedContext)!
        let productEntity = NSEntityDescription.entity(forEntityName: "Product", in: managedContext)!

        // Setting the default company data (name, logo, and stockPrice)
        let url = URL(string: "https://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20Ask%2C%20YearHigh%2C%20YearLow%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22%2C%22GOOG%22%2C%22TWTR%22%2C%22TSLA%22%2C%20%22FB%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys")!
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error!)
            } else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
                let json = JSON(data: data!)
                if let quotes = json["query"]["results"]["quote"].array {
                    for quote in quotes {
                        let symbol = quote["symbol"].stringValue
                        let name = NSLocalizedString(symbol, comment:"")
                        let ask = quote["Ask"].stringValue
                        let company = NSManagedObject(entity: companyEntity,insertInto: managedContext)
                        company.setValue(name, forKey: "name")
                        company.setValue(name, forKey: "logo")
                        company.setValue(ask, forKey: "stockPrice")
                        companies.append(company)

                        let companyProducts = defaultProducts[name]

                        for productName in companyProducts! {

                            let product = NSManagedObject(entity: productEntity, insertInto:managedContext)
                            let names = urlDictionary[productName]

                            product.setValue(productName, forKey: "name")
                            product.setValue(productName, forKey: "image")
                            product.setValue(names, forKey: "url")

                            product.setValue(company, forKey: "company")

                        }
                        print(json)
                    }

                    DispatchQueue.main.async {
                        do {
                            try managedContext.save()
                            vc.tableView.reloadData()
                            userDefaults.set(false, forKey: "firstRun")
                        } catch let error as NSError {
                            print("Could not save. \(error), \(error.userInfo)")
                        }
                    }
                }
            } else {
                print("The data couldn't be loaded")
            }
        }
        task.resume()
    }
}

1 个答案:

答案 0 :(得分:1)

许多问题更加复杂:

  1. didSelectRowAt代码正在创建新的Product个实例,而不是根据点击的行使用正确的Product。解决这个问题的方法是替换:

    let product = NSManagedObject(entity: entity, insertInto: managedContext)
    

    使用:

    let product = products[indexPath.row]
    
  2. 该代码还假设url实体的Product属性属于URL类型;实际上它是String类型。解决此问题的方法是更正演员表,然后从URL创建String

    if let urlString = product.value(forKey: "url") as? String {
        let url = URL(string:urlString)
    
  3. 最后,NSLocalizedStrings在创建默认数据时导致了问题。通过用字典替换它们来解决这个问题:

    let urlDictionary = ["iPhone" : "http://www.apple.com/iphone/", 
                         "iPad" : "http://www.apple.com/ipad/", etc
    

    然后:

    let names = urlDictionary[productName]