是否可以为Alamofire请求添加超时处理程序?
在我的项目中,我使用Alamofire:
init() {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.timeoutIntervalForRequest = 30
self.alamofireManager = Alamofire.Manager(configuration: configuration)
}
func requestAuthorizationWithEmail(email:NSString, password:NSString, completion: (result: RequestResult) -> Void) {
self.alamofireManager!.request(.POST, "myURL", parameters:["email": email, "password":password])
.responseJSON { response in
switch response.result {
case .Success(let JSON):
//do json stuff
case .Failure(let error):
print("\n\nAuth request failed with error:\n \(error)")
completion(result: .ConnectionFailed)
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
请求失败消息
错误域= NSURLErrorDomain代码= -1001"请求超时." UserInfo = {NSUnderlyingError = 0x7fc10b937320 {Error Domain = kCFErrorDomainCFNetwork Code = -1001"(null)"UserInfo = {_ kCFStreamErrorCodeKey = -2102,_kCFStreamErrorDomainKey = 4}},NSErrorFailingURLStringKey = url,NSErrorFailingURLKey = url,_kCFStreamErrorDomainKey = 4,_kCFStreamErrorCodeKey = -2102 ,NSLocalizedDescription =请求超时.}
kam*_*soc 84
您可以比较error._code,如果它等于-1001哪个,NSURLErrorTimedOut那么您知道这是一个超时.
Swift 3,Alamofire 4.0.1
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 120
manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])
.responseJSON {
response in
switch (response.result) {
case .success: // succes path
case .failure(let error):
if error._code == NSURLErrorTimedOut {
print("Request timeout!")
}
}
}
Run Code Online (Sandbox Code Playgroud)
Swift 2.2
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 120
manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])
.responseJSON {
response in
switch (response.result) {
case .success: // succes path
case .failure(let error):
if error._code == NSURLErrorTimedOut {
print("Request timeout!")
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ani*_*eja 21
斯威夫特3
接受的答案对我没有用.
经过大量的研究,我确实喜欢这个.
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 120
manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])
Run Code Online (Sandbox Code Playgroud)
ivo*_*oto 11
我想为我的项目中的每个HTTP调用设置相同的超时.
关键的想法是将Alamofire会话管理器 声明为全局变量.然后创建URLSessionConfiguration变量,以秒为单位设置其超时并将其分配给管理器.
项目中的每个调用都可以使用此配置的会话管理器.
在我的例子中,全局Alamofire会话管理器变量在AppDelegate文件中设置(全局),其配置在其didFinishLaunchingWithOptions方法中进行管理
AppDelegate.swift
import UIKit
var AFManager = SessionManager()
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 4 // seconds
configuration.timeoutIntervalForResource = 4 //seconds
AFManager = Alamofire.SessionManager(configuration: configuration)
return true
}
...
}
Run Code Online (Sandbox Code Playgroud)
从现在开始,可以使用afManager从应用程序的任何部分调用Alamofire请求函数.
例如:
AFManager.request("yourURL", method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseJSON { response in
...
}
Run Code Online (Sandbox Code Playgroud)
斯威夫特 5、阿拉莫菲尔 5
我发现的适用于最新版本 Alamofire 的最简洁的方法如下:
AF.request(url).response { (dataResponse: AFDataResponse<Data?>) in
switch dataResponse.result {
case .success(let data):
// succes path
case .failure(let error):
switch error {
case .sessionTaskFailed(URLError.timedOut):
print("Request timeout!")
default:
print("Other error!")
}
}
}
Run Code Online (Sandbox Code Playgroud)
斯威夫特 3.x
class NetworkHelper {
static let shared = NetworkHelper()
var manager: SessionManager {
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 10
return manager
}
func postJSONData( withParams parameters: Dictionary<String, Any>, toUrl urlString: String, completion: @escaping (_ error: Error,_ responseBody: Dictionary<String, AnyObject>?)->()) {
manager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
if let error = response.result.error {
if error._code == NSURLErrorTimedOut {
print("Time out occurs!")
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39872 次 |
| 最近记录: |