2017-10-14 1 views
0

네트워크 요청에 Alamofire를 사용하고 있으며 시간 제한을 추가하려고합니다. 그러나 Alamofire의 기능은 작동하지 않습니다. 다음 코드를 작성할 때 아무런 반응이 없습니다.Alamofire timeout이 Swift 3에서 작동하지 않습니다.

let manager = Alamofire.SessionManager.default 
    manager.session.configuration.timeoutIntervalForRequest = 1 // not working, 20 secs normally (1 just for try) 

    manager.request(url, method: method, parameters: params) 
     .responseJSON { response in 
      print(response) 
      ... 

네트워크 요청을 위해 Alamofire없이 시도하면, 시간 초과가 성공적으로 작동합니다. 그러나 다른 실수가 있습니다. 그래서

var request = URLRequest(url: URL(string: url)!) 
request.httpMethod = "post" 
request.setValue("application/json", forHTTPHeaderField: "Content-Type") 
request.timeoutInterval = 1 // 20 secs normally (1 just for try) 
request.httpBody = try! JSONSerialization.data(withJSONObject: params!) 
...  

, 내가 어떻게 스위프트 3 Alamofire에 대한 시간 제한을 추가 할 수 있습니까? 이 때문에 Alamofire.SesssionManager.default.session.configuration 항상 실패 조작을 시도하는 URLSession에 추가 한 후

답변

0

마지막으로 나는이 답변에 해결책을 발견 : 나는 AppDelegate에에 추가 할 때 작동 내 기능, 하지만 를 추가 할 때 https://stackoverflow.com/a/44948686/7825024

이 구성 코드는 작동하지 않습니다!

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 = 5 // seconds 
     configuration.timeoutIntervalForResource = 5 //seconds 
     AFManager = Alamofire.SessionManager(configuration: configuration) 

     return true 
    } 
    ... 
} 

예 :

AFManager.request("yourURL", method: .post, parameters: parameters).responseJSON { response in 
    ... 
} 
0

당신은 URLSessionConfiguration의 값을 수정할 수 없습니다. 구성 값을 올바르게 변경하려면 Alamofire 설명서를 참조하여 자신의 SessionManager을 인스턴스화하십시오. 예를 들어 :

var defaultHeaders = Alamofire.SessionManager.defaultHTTPHeaders 
defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" 

let configuration = URLSessionConfiguration.default 
configuration.httpAdditionalHeaders = defaultHeaders 

let sessionManager = Alamofire.SessionManager(configuration: configuration) 
관련 문제