0

My friend and I are working on an app using git. We've encountered a strange problem, when the code runs on my computer but doesn't on hers. Here's the code:

import UIKit

class SelectionViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        //adding table
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

        // HTTP POST
        let myURL = NSURL(string: "http://.../drinks.php")

        let request = NSMutableURLRequest(URL:myURL!)

        request.HTTPMethod = "POST"

        let postString = ""

        print(postString)

        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

        NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
            (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in


            dispatch_async(dispatch_get_main_queue())
            {

                do {
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                    if let parseJSON = json {


                        // Store the variables locally
                        NSUserDefaults.standardUserDefaults().setObject(parseJSON["Selection"], forKey: "items")
                        NSUserDefaults.standardUserDefaults().setObject(parseJSON["Details"], forKey: "details")
                        //NSUserDefaults.standardUserDefaults().synchronize()
                    }
                } catch
                {
                    print(error)
                }
            }
        }).resume()
    }

    // Grab the values from the local storage and declare them locally
    var details = (NSUserDefaults.standardUserDefaults().stringArrayForKey("details"))!
    var items = (NSUserDefaults.standardUserDefaults().stringArrayForKey("items"))!

It breaks on the last two lines saying: fatal error: unexpectedly found nil while unwrapping an Optional value:

    var details = (NSUserDefaults.standardUserDefaults().stringArrayForKey("details"))!
    var items = (NSUserDefaults.standardUserDefaults().stringArrayForKey("items"))!

Any help will be highly appreciated!

Misha
  • 163
  • 1
  • 1
  • 12
  • What do you expect to happen when there is no string array for the key `"details"` or `"items"`? – Alexander Aug 16 '16 at 16:59
  • This sounds like it might be an issue with Git messing with the line endings differently on your computers. Swift might expect a certain type of line ending, even more so because it is an iOS language and Apple is meticulous about this. Check out the answer by @VonC for more information: http://stackoverflow.com/questions/2825428/why-should-i-use-core-autocrlf-true-in-git – Tim Biegeleisen Aug 16 '16 at 17:00
  • Please, please, please don't use forced unwrapping (`!`) - every second question on this topic is caused by wrong use of it. It should only ever be used when you, the programmer, can *prove* that the value can *never* be `nil`. – Grimxn Aug 16 '16 at 17:01
  • @AlexanderMomchliov I'm probably wrong, but I thought that this is where my string array is coming from: NSUserDefaults.standardUserDefaults().setObject(parseJSON["Selection"], forKey: "items") – Misha Aug 16 '16 at 17:11
  • 1
    Always register default values for all keys in `NSUserDefaults` as Apple [recommends](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/UserDefaults/AccessingPreferenceValues/AccessingPreferenceValues.html) (but almost nobody does), then you never get `nil` even when the property list file will be deleted. Especially in Swift this is a huge benefit. – vadian Aug 16 '16 at 17:11
  • PS: And if you expect that the lines to read from user defaults are executed **after** they are written in `dataTaskWithRequest` you are wrong. By the way `NSUserDefaults` is **not** the right place to store temporary data. – vadian Aug 16 '16 at 17:22
  • @vadian thanks! Can you please explain why I am wrong? I'm new to swift and not fully understand your answer. I also don't understand why it does work on my computer.. – Misha Aug 16 '16 at 18:08
  • `dataTaskWithRequest` works asynchronously. The completion block is always executed after the method exits and therefore after the code following `resume`. It **seems** to work on your computer because there are values for keys `details` and `items` in `NSUserDefaults` but the values are not those retrieved in the data task. – vadian Aug 16 '16 at 18:14
  • @vadian oh now I understand and am getting the same error (I cleared my `NSUserDefaults`)! Thanks for your help! If you don't mind, where in the code should I retrieve the data from `NSUserDefaults`? – Misha Aug 16 '16 at 18:43
  • As already mentioned you should **not** use `NSUserDefaults` to store temporary data. Basically execute the code the process the received data right in the completion block of the data task. – vadian Aug 16 '16 at 19:13

0 Answers0