NSURLSession超时 [英] NSURLSession timeout

查看:323
本文介绍了NSURLSession超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,我可以在其中请求获取JSON.

I have a function where I make a request to get a JSON.

let request = NSMutableURLRequest(URL: NSURL(string: path)!)
let session = NSURLSession.sharedSession()

session.configuration.timeoutIntervalForRequest = 5
session.configuration.timeoutIntervalForResource = 5

let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
     let json:JSON = JSON(data: data!)
     onCompletion(json, error)
})
task.resume()

这可行,但是我在超时方面遇到了问题.如果请求花费了5秒钟以上,我想取消该操作.任何想法如何做到这一点?

This works, but I´m having issues with the timeout. If the request takes more than 5 seconds I want to cancel the operation. Any ideas how to do this?

该呼叫可能需要5秒钟以上的时间,但仍然会触发并且超时不会执行任何操作.如果超时被触发,我需要做任何事情吗?

The call can take more than 5 seconds but it stills fires and the timeout does not do anything. Do I have to do anything if the timeout is fired?

更新

        let request = NSMutableURLRequest(URL: NSURL(string: path)!)

        let urlconfig = NSURLSessionConfiguration.defaultSessionConfiguration()
        urlconfig.timeoutIntervalForRequest = 5
        urlconfig.timeoutIntervalForResource = 5
        let session = NSURLSession(configuration: urlconfig, delegate: self, delegateQueue: nil)

        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            let json:JSON = JSON(data: data!)
            onCompletion(json, error)
        })
        task.resume()

推荐答案

您不能更改sharedSession或会话configuration属性的超时.创建会话时,您必须设置超时.参见以下示例,了解如何创建会话及其超时: https://stackoverflow.com/a/30427187/78496

You cannot change the timeout on the sharedSession or a sessions configuration property. You have to set the timeout when the session is created. See this for an example of how to create a session and its timeout: https://stackoverflow.com/a/30427187/78496

这篇关于NSURLSession超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆