unexpectedly found nil while unwrapping an Optional value - Using ALAMOFIRE

ⅰ亾dé卋堺 提交于 2019-12-10 17:16:58

问题


I am trying to use Alamofire for GETs in JSON. When I use one URL - It works fine and when I use another I get an error unwrapping an optional value. I cannot seem to track where the error is coming from. I have resorted in putting the code in ViewDidLoad to track the error. I don't know if its the recipient and they want some sort of authorisation. but I know its not the println's cos when i // them - it still comes up as an error , heres the code :

request(.GET, "https://api.doingdata.net/sms/send?api_service_key='APIKey'&msg_senderid=Edify-FYI&msg_to=&msg_text={otp|Edify-FYI|3600|ETEN|4} &msg_clientref=abcdef123456&msg_dr=0&output=json")
        .validate()
        .responseJSON { (_, _, _, error) in
            println(error)
    }

but I use :

request(.GET, "http://httpbin.org/")
            .validate()
            .responseJSON { (_, _, _, error) in
                println(error)
        }

it works fine and returns nil for the error.

Any help would be great, as its driving me nuts.


回答1:


The reason is simple: your URL has special characters. So, if you do

let url = NSURL(string:yourURLString) //returns nil

It will return nil. You would need to format your URL to be suitable for making requests. Here is one solution for you.

var urlString = "https://api.doingdata.net/sms/send?api_service_key='APIKey'&msg_senderid=Edify-FYI&msg_to=&msg_text={otp|Edify-FYI|3600|ETEN|4} &msg_clientref=abcdef123456&msg_dr=0&output=json"
urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
request(.GET, urlString, parameters: nil, encoding: .JSON)


来源:https://stackoverflow.com/questions/29168068/unexpectedly-found-nil-while-unwrapping-an-optional-value-using-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!