最近在研究RxSwift,用Alamofire请求数据,Alam他默认timeout时间是30s,我想把他改成15s于是就这样:
static func request(N: YYAPI) -> Observable<YYResult> {
return Observable<YYResult>.create { (obser) -> Disposable in
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 15
let manager = Alamofire.SessionManager(configuration: config)
manager.request(N.path, method: N.method, parameters: N.param, encoding: URLEncoding.default, headers: nil)
.responseJSON(completionHandler: { (response) in
var result = YYResult()
switch response.result{
case .success(let value):
result.data = value
obser.onNext(result)
case .failure(let error):
obser.onError(error)
}
})
return Disposables.create {
}
}
}
无论我怎样试结果都是code=-999 cancelled
FAILURE: Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey=http://sssss/api/api_open.php?a=list&c=data&page=1&type=29, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=http://sssss/api/api_open.php?a=list&c=data&page=1&type=29}
于是就翻阅资料才发现,自定义的manager必须是强引用,于是改一下
static var manger:SessionManager? = nil
static func request(N: YYAPI) -> Observable<YYResult> {
return Observable<YYResult>.create { (obser) -> Disposable in
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 15
manger = Alamofire.SessionManager(configuration: config)
manger?.request(N.path, method: N.method, parameters: N.param, encoding: URLEncoding.default, headers: nil)
.responseJSON(completionHandler: { (response) in
var result = YYResult()
switch response.result{
case .success(let value):
result.data = value
obser.onNext(result)
case .failure(let error):
obser.onError(error)
}
})
return Disposables.create {
}
}
}
这样就能请求成功了
最近在看RxSwift...