简体   繁体   中英

Found nil when unwrapping non nil value

I'm trying to make a get request in swift passing the following parameters

var dict = [
    "id_struttura" : 2,
    "prenCheck" : [
        "codice" : "14:30_15:20_1_3831_0",
        "id_sport" : 6,
        "ora_fine" : "20/02/2015 15:20:00",
        "ora_inizio" : "20/02/2015 14:30:00",
        "rec" : 0,
        "soci" : [
            [
                "esterno" : 0,
                "id" : "1980"
            ],
            [
                "esterno" : 0,
                "id" : "51"
            ]
        ]
    ]
]

using the following method:

private func genericRequest(method: Methods, url: String, data: [String: AnyObject]?) -> AnyObject?{
    var getRequest : NSURLRequest?
    var postRequest : NSMutableURLRequest?

    if method == Methods.GET{
        var completeUrl = url

        if(data != nil){
            //println(data)
            completeUrl += "?"
            for (key, value) in data! {

                completeUrl += "\(key)=\(value)&"
            }
            completeUrl = completeUrl.substringToIndex(completeUrl.endIndex.predecessor())
        }
        //println(completeUrl)

        let url = NSURL(string: completeUrl)
        getRequest = NSURLRequest(URL: url!)

    }else if method == Methods.POST{
        postRequest = NSMutableURLRequest(URL: NSURL(string: url)!)
        var session = NSURLSession.sharedSession()
        postRequest!.HTTPMethod = "POST"

        var params : String = ""

        for (key, value) in data! {

            params += "\(key)=\(value)&"
        }
        params = params.substringToIndex(params.endIndex.predecessor())

        var err: NSError?
        postRequest!.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding);
    }

    var response: NSURLResponse? = nil
    var error: NSError? = nil
    var request = getRequest != nil ? getRequest! : postRequest!
    let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)

    //println((response as NSHTTPURLResponse).statusCode)
    let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
    var json: AnyObject? = convertDataToJSON(reply)
    return json
}

calling it as genericRequest(Method.GET ,url:url, data: dict) (as Method is simply an enum) it can't unwrap the data variable in for (key,value)in data! when making a get request, but it can when it's making a post request. Since I have to use only get requests for this task (i'm dealing with a bad rest interface), could someone help me?

UPDATE: I also tried with if let data = data { ... and it crashes on this line saying unexpectedly found nil while unwrapping an Optional value

You are using a lot of force unwrapping ( ! ). Each place where you do that is a place where you are promising the compiler that the optional will never ever be nil. In most places I think that you should allow the compiler to prove the nil safety by using other methods of dealing with optionals (optional chaining, nil coalescing, map etc.)

In your specific case I don't know why you aren't doing:

if let data = data {

instead of:

if (data != nil) {

and then having to force unwrap data with ! .

I recently blogged and talked about the tools for dealing with optionals in Swift if you want more information about how not force unwrap.

Why you are not checking if data is nil in your POST method as you did in GET method. I think the post method is where you are trying to unwrap nil

if method == Methods.GET{
    var completeUrl = url

    // here you check if data is nil
    if(data != nil){
        //println(data)
        completeUrl += "?"
        for (key, value) in data! {

            completeUrl += "\(key)=\(value)&"
        }
        completeUrl = completeUrl.substringToIndex(completeUrl.endIndex.predecessor())
    }
    //println(completeUrl)

    let url = NSURL(string: completeUrl)
    getRequest = NSURLRequest(URL: url!)

}else if method == Methods.POST{
    postRequest = NSMutableURLRequest(URL: NSURL(string: url)!)
    var session = NSURLSession.sharedSession()
    postRequest!.HTTPMethod = "POST"

    var params : String = ""
    //check here as well
    if data != nil{
        for (key, value) in data! {

            params += "\(key)=\(value)&"
        }
        params = params.substringToIndex(params.endIndex.predecessor())
    }

    var err: NSError?
    postRequest!.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM