web-dev-qa-db-ja.com

Alamofireでタイムアウトを設定する

Alamofire 4.0.1を使用しており、リクエストのタイムアウトを設定したい私はこれで与えられた解決策を試しました 質問

最初の場合NSURLErrorDomain(タイムアウトが正しく設定されています):

let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10

    let sessionManager = Alamofire.SessionManager(configuration: configuration)
    sessionManager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])
            .responseJSON {
                response in
                switch (response.result) {
                case .success:
                    //do json stuff
                    break
                case .failure(let error):
                    if error._code == NSURLErrorTimedOut {
                        //timeout here
                    }
                    print("\n\nAuth request failed with error:\n \(error)")
                    break
                }
            }

2番目の場合、タイムアウトは置き換えられず、60秒に設定されたままです。

let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 10

manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])

iOS 10.1で実行しています

私のコード:(動作しません)

    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 10 // seconds
    configuration.timeoutIntervalForResource = 10
    let alamoFireManager = Alamofire.SessionManager(configuration: configuration)

    alamoFireManager.request("my_url", method: .post, parameters: parameters).responseJSON { response in


        switch (response.result) {
        case .success:
                 //Success....
            break
        case .failure(let error):
            // failure...
            break
        }
    }

解決済みのAlamofire githubスレッド:Alamofire 4.3.0タイムアウトの設定でNSURLErrorDomainエラー#1931

32
ƒernando Valle

@ kamal-thakur応答に基づきます。

Swift

var request = URLRequest(url: NSURL.init(string: "YOUR_URL") as! URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.timeoutInterval = 10 // 10 secs
let postString = "param1=\(var1)&param2=\(var2)"
request.httpBody = postString.data(using: .utf8)
Alamofire.request(request).responseJSON {
    response in
    // do whatever you want here
}
7
ƒernando Valle

これを試してください:-

    let request = NSMutableURLRequest(url: URL(string: "")!)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.timeoutInterval = 10 // 10 secs
    let values = ["key": "value"]
    request.httpBody = try! JSONSerialization.data(withJSONObject: values, options: [])
    Alamofire.request(request as! URLRequestConvertible).responseJSON {
        response in
        // do whatever you want here
    }
25
Kamal Thakur

私も同じ問題を抱えています。解決策を見つけたと思います。 SessionManager?orまたはあなたのケースではalamofireManagerをクラスの関数外で宣言してください

class ViewController: UIViewController {
   var alamoFireManager : SessionManager? // this line

   func alamofire(){
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 10
        configuration.timeoutIntervalForResource = 10
        alamoFireManager = Alamofire.SessionManager(configuration: configuration) // not in this line

        alamoFireManager.request("my_url", method: .post, parameters: parameters).responseJSON { response in


        switch (response.result) {
        case .success:
                 //Success....
            break
        case .failure(let error):
               // failure...
             break
       }
     }
   }

}
18
Aldo Lazuardi

これを試して:

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForRequest = 4 // seconds
    configuration.timeoutIntervalForResource = 4
    self.alamoFireManager = Alamofire.Manager(configuration: configuration)

Swift 3.

    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 4 // seconds
    configuration.timeoutIntervalForResource = 4
    self.alamoFireManager = Alamofire.SessionManager(configuration: configuration)
11
Jason Bourne

Alamofireの1つのインスタンスを使用している場合、次のような遅延変数を作成できます。

   private lazy var alamoFireManager: SessionManager? = {
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 5
    configuration.timeoutIntervalForResource = 5
    let alamoFireManager = Alamofire.SessionManager(configuration: configuration)
    return alamoFireManager

}()

Swift 4.2で動作します

8
Letaief Achraf

マットが言ったように、問題は次のとおりです

ここでの違いは、初期化されたマネージャーが所有されておらず、スコープ外になった直後に割り当て解除されることです。その結果、保留中のタスクはキャンセルされます。

この問題の解決策はrainypixelsによって書かれました

import Foundation import Alamofireをインポートする

class NetworkManager {

    var manager: Manager?

    init() {
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        manager = Alamofire.Manager(configuration: configuration)
    }
}

そして私自身のバージョン

class APIManager {

    private var sessionManager = Alamofire.SessionManager()

    func requestCards(_ days_range: Int, success: ((_ cards: [CardModel]) -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.global(qos: .background).async {
            let parameters = ["example" : 1]

            let headers = ["AUTH" : "Example"]

            let configuration = URLSessionConfiguration.default
            configuration.timeoutIntervalForRequest = 10
            self.sessionManager = Alamofire.SessionManager(configuration: configuration)

            self.sessionManager.request(URLs.cards.value, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON { (response) in
                switch response.result {
                case .success:
                    //do json stuff
                    guard let json = response.result.value as? [String : Any] else { return }
                    guard let result = json["result"] as? [[String : Any]] else { return }
                    let cards = Mapper<CardModel>().mapArray(JSONArray: result)
                    debugPrint("cards", cards.count)
                    success?(cards)
                case .failure(let error):
                    if error._code == NSURLErrorTimedOut {
                        //timeout here
                        debugPrint("timeOut")
                    }
                    debugPrint("\n\ncard request failed with error:\n \(error)")
                    fail?(error)
                }
            }
        }
    }
}

マネージャーを作ることもできます

import Alamofire

struct AlamofireAppManager {

    static let shared: SessionManager = {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 10
        let sessionManager = Alamofire.SessionManager(configuration: configuration)
        return sessionManager
    }()

}
8

たくさんの試行の後、私は次のものでそれを作りました:

var timeout = 300 // 5 minutes

//Post values
    let parameters:Parameters = parameters

    //Server value
    let url:URL = (url)


    //Make the request
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForResource = TimeInterval(timeout)
    configuration.timeoutIntervalForRequest = TimeInterval(timeout)

    let sessionManager = Alamofire.SessionManager(configuration: configuration)

     sessionManager.request(url,parameters:parameters).validate(statusCode: 200..<300).responseJSON { response in


        print(response.request)  // original URL request
        print(response.response) // URL response

        print(sessionManager.session.configuration.timeoutIntervalForRequest)   // result of response time
        print(response.timeline.totalDuration)


        switch response.result {
        case .success:

            if let valJSON = response.result.value {


               //use your json result 



            }

        case .failure (let error):

            print("\n\nAuth request failed with error:\n \(error)")

        }
    }

私はそれが役立つことを願っています;)

2
Edgar Estrada

上記のどれも私のために働いていません:Swift 4.2Alamofire 4.5のIm

私はこのようにそれを解決することができました:

let request = Alamofire.request("routee", method: .post, parameters: data, encoding: JSONEncoding.default, headers: getHeaders())

/// getting request created by Alamofire and then updating its timeout Value

let url = URL(string: "myroute")!
        var request = try URLRequest(url: url, method: method, headers: headers)
        request.timeoutInterval = 900 // timeout
        request = try JSONEncoding.default.encode(request, with: data)

Alamofire.request(request)
    .responseJSON { response in

}
0
brahimm

私はSwift 2.3のコードを持っています

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForResource = 10800 // seconds
    configuration.timeoutIntervalForRequest = 10800 // seconds

    alamoFireManager = Alamofire.Manager(configuration: configuration)
0
Patel Jigar

UrlRequestを自分でビルドしたくない場合でも、Alamofireを使用してビルドできます。

    // set this flag to false so the request will not be sent until
    // resume() is called
    sessionManager.startRequestsImmediately = false

    var urlRequest = sessionManager.request(url,
                                            method: method,
                                            parameters: params,
                                            encoding: encoding,
                                            headers: allHeaders).request!

    urlRequest.timeoutInterval = 10

    let request = sessionManager.request(urlRequest).responseJSON { (result) in
        // use the result
    }

    // need to start the request
    request.resume()
0
ukim

それは私のために働いています:

let url:String = "http://..."
let request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Kirk Hamet", forHTTPHeaderField:"name")
request.timeoutInterval = 23 //Second

Alamofire.request(request).responseJSON {
                response in
    if response.result.isSuccess == true {

    }else{

    }

}

Swift 4.1

0
reza_khalafi