user2722667
user2722667

Reputation: 8661

Swift Alamofire quit when request timed out

I wonder how I can exit out of my function when request timed out. If I put my server offline and try to do some calls with this function the app will crash due to: fatal error: unexpectedly found nil while unwrapping an Optional value

My Alamofire v3.x function looks like this:

static func loginWithFb(facebookId: String, email: String, username: String, response: (token: String?, errorVal: JSON?) -> ()) {
        let urlString = baseURL + ResourcePath.FbLogin.description

        let parameters: [String: AnyObject] = [
            "facebook_id": facebookId,
            "user_type": 1,
            "email": email,
            "username": username
        ]
        Alamofire.request(.POST, urlString, parameters: parameters).responseJSON{ (responseData) -> Void in

            let json = JSON(responseData.result.value!)

            let token = json["api_key"].string
            response(token: token, errorVal: json)
        }

    }

I get nil from: let json = JSON(responseData.result.value!)

and the error:

FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7fc39349c4a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://mysite.dev/fb, NSErrorFailingURLKey=http://mysite.dev/fb,
_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}
fatal error: unexpectedly found nil while unwrapping an Optional value

So how can I exit the call if the request timed out? preventing it from trying to get the json data

Thanks,

Upvotes: 2

Views: 3409

Answers (3)

Ashish Kakkad
Ashish Kakkad

Reputation: 23882

You can increase the timeout interval if your service getting long time.

let request = NSMutableURLRequest(URL: NSURL.init(string: "your url")!)
request.HTTPMethod = "GET"
request.timeoutInterval = 250 // Set your timeout interval here.

Alamofire.request(request).responseJSON { (responseData) -> Void in
    if((responseData.result.value) != nil) { //Check for response
        print(responseData.result.value!)
    }
}

And must check that the response is not nil to resolve the issue of fatal error.

Upvotes: 4

Sean Lintern
Sean Lintern

Reputation: 3141

Your issue is here

        let json = JSON(responseData.result.value!)

you are force unwrapping value! instead you should wrap it in an if let

 if let json = JSON(responseData.result.value) as? NSDictionary {
            let token = json["api_key"].string
            response(token: token, errorVal: json)
 }

The timeout is fine and is not effecting your app in any way.

Upvotes: 1

DeyaEldeen
DeyaEldeen

Reputation: 11817

you need to know more about swift variable unwrapping, just a simple if(myJsonData != nil) would prevent the app crash, you can also add an alert box in case that there is no data on server or the server is down etc...

static func loginWithFb(facebookId: String, email: String, username: String, response: (token: String?, errorVal: JSON?) -> ()) {
            let urlString = baseURL + ResourcePath.FbLogin.description

            let parameters: [String: AnyObject] = [
                "facebook_id": facebookId,
                "user_type": 1,
                "email": email,
                "username": username
            ]
            Alamofire.request(.POST, urlString, parameters: parameters).responseJSON{ (responseData) -> Void in

                let myJsonData = JSON(responseData.result.value!)

                if(myJsonData != nil)
                {
                    let token = myJsonData["api_key"].string
                }
                else
                {
                    // show alert box
                }
            }

        }

Upvotes: 1

Related Questions