0

I want a view to move up when toggling the keyboard. It works in all my other views but in this one it doesn't work. It says "unexpectedly found nil while unwrapping an Optional value"

Here is my code:

class SecondViewController: UIViewController , UIPickerViewDelegate, UIPickerViewDataSource{


@IBOutlet var ScrollView: UIScrollView!
@IBOutlet weak var codeaffiche: UILabel!

@IBOutlet var Prix: UITextField!
@IBOutlet var NomProduit: UITextField!
@IBOutlet var picker1: UIPickerView!
@IBOutlet var NomMAG: UITextField!
var nom_magasin :String!
var pickerData = [String]()
var pickerDataRow = [String]()
override func viewDidLoad() {
    super.viewDidLoad()
    codeaffiche.text = detectionString 

    NomMAG.alpha = 0
    let str = "http://vps43623.ovh.net/yamoinscher/api/getAllMag"
    let url = NSURL(string: str)!

    let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
        if let urlContent = data {
            do {
                let jsonObject = try NSJSONSerialization.JSONObjectWithData(urlContent, options: [])
                if let jsonResult = jsonObject as? [String:AnyObject],
                    magasin = jsonResult["magasin"] as? [[String:String]] {
                        // filter valid items, map them to an array and filter empty strings
                        self.pickerData = magasin.filter { $0["libelle"] != nil }.map { $0["libelle"]! }.filter { !$0.isEmpty}
                        self.pickerDataRow = magasin.filter { $0["id"] != nil }.map { $0["id"]! }.filter { !$0.isEmpty}
                    self.pickerData.append("choisir magasin")
                }
                dispatch_async(dispatch_get_main_queue()) {

                    self.picker1.reloadAllComponents()
                }
            } catch {
                print("JSON serialization failed", error)
            }
        } else if let connectionError = error {
            print("connection error", connectionError)
        }

    }

    task.resume()

}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    ScrollView.keyboardDismissMode = .OnDrag

}
func textFieldShouldReturn(textField: UITextField) -> Bool {

    textField.resignFirstResponder()
    return true
}
func textFieldDidBeginEditing(textField: UITextField) {

    if textField ==  NomMAG {

    ScrollView.setContentOffset(CGPointMake(0, 250), animated: true)
    }
}
func textFieldDidEndEditing(textField: UITextField) {
     if textField ==  NomMAG {
    ScrollView.setContentOffset(CGPointMake(0,0), animated: true)
    }
}



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// The number of columns of data
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

// The number of rows of data
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return self.pickerData.count
}

// The data to return for the row and component (column) that's being passed in


 func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    return self.pickerData[row]
}


func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {



    if pickerData[row] == "choisir magasin"
    {
        //print(row)

        NomMAG.alpha = 1
        nom_magasin = NomMAG.text
    }
    else
    {
        //print(row.description)
        NomMAG.alpha = 0
        nom_magasin = pickerData[row]
    }



}


@IBAction func AddProduct(sender: AnyObject) {

    let myUrl = NSURL(string: "http://vps43623.ovh.net/yamoinscher/ios/products/addIos");let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "POST";
    // Compose a query string
    let postString = "code_barre=\(detectionString!)&&libelle=\(NomProduit.text!)&nom_magasin=\(nom_magasin!)&prix=\(Prix.text!)"
    let postLength = String(postString.characters.count)

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

    request.setValue(postLength, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {

        data, response, error in

        if error != nil
        {
            print("error=\(error)")
            return
        }

        // print out response object
        print("response = \(response)")

        // Print out response body
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")


    }
    task.resume()

}

}
dehlen
  • 7,325
  • 4
  • 43
  • 71
  • Are all the outlets connected properly? – Devster101 Jun 10 '16 at 13:47
  • Is your storyboard outlet is connected properly? – Nirav D Jun 10 '16 at 13:51
  • I would also guess that you forgot to connect one of your IBOutlets. By the way when you want to move your view when the keyboard is toggled I would recommend to observe the specific NSNotifications and use the info dictionary which is passed to retrieve the keyboard height. You can find multiple answers concerning this, for example: http://stackoverflow.com/questions/25451001/getting-keyboard-size-from-userinfo-in-swift – dehlen Jun 10 '16 at 13:52
  • can you put here your crash stack trace? – Reinier Melian Jun 10 '16 at 19:37
  • I fixed it just by reconnecting my iboutlets :) – Marwen Jamel Jun 10 '16 at 19:43

0 Answers0