【问题标题】:How to use singleton with Alamofire using Swift 3?如何使用 Swift 3 将单例与 Alamofire 一起使用?
【发布时间】:2016-12-21 10:18:20
【问题描述】:

我是 iOS 新手,我对如何在 Alamofire 中使用单例以及单例的重要性感到有些困惑。我创建了一个 networkWrapper 类,其中我编写了 Alamofire post 和 get 方法,但我没有使用单例。

如何使用单例创建 Alamofire 的 Wrapper 类?我怎样才能获得所有真正重要的技巧?

下面是我的包装类代码:

import Foundation
import UIKit
import Alamofire
import SwiftyJSON

class AFWrapper: NSObject {

//TODO :-
/* Handle Time out request alamofire */


 class func requestGETURL(_ strURL: String, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void)
    {
        Alamofire.request(strURL).responseJSON { (responseObject) -> Void in
            //print(responseObject)
            if responseObject.result.isSuccess {
                let resJson = JSON(responseObject.result.value!)
                //let title = resJson["title"].string
                //print(title!)
                success(resJson)
            }

        if responseObject.result.isFailure {
            let error : Error = responseObject.result.error!
            failure(error)
        }
    }
  }

static func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void){
    Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in
        //print(responseObject)
        if responseObject.result.isSuccess {
            let resJson = JSON(responseObject.result.value!)
            success(resJson)
        }
        if responseObject.result.isFailure {
            let error : Error = responseObject.result.error!
            failure(error)
        }
    }
  }
}  

在我的控制器中:

           if newLength == 6
            {
                let textZipCode = textField.text! + string

                let dict = ["id" : "43","token": "2y103pfjNHbDewLl9OaAivWhvMUp4cWRXIpa399","zipcode" : textZipCode] as [String : Any]

                //Call Service
               AFWrapper.requestPOSTURL(HttpsUrl.Address, params: dict as [String : AnyObject]?, headers: nil, success: { (json) in
                    // success code
                    print(json)
                }, failure: { (error) in
                    //error code
                    print(error)
                })


                setFields(city: "Ajmer", state: "Rajasthan", country: "India")
                return newLength <= 6
            }

【问题讨论】:

    标签: ios swift http singleton alamofire


    【解决方案1】:

    我没有深入研究您的代码。在swift中,我们可以通过

    创建单例
    static let sharedInstance = AFWrapper()
    

    并且它会创建一个类的单例实例,这样单例类实例函数的类和静态就不是必需的了。请参考下面的单例类代码。

    import Foundation
    import UIKit
    import Alamofire
    import SwiftyJSON
    
    class AFWrapper: NSObject {
    
        static let sharedInstance = AFWrapper()
    
        //TODO :-
        /* Handle Time out request alamofire */
    
    
        func requestGETURL(_ strURL: String, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void)
        {
            Alamofire.request(strURL).responseJSON { (responseObject) -> Void in
                //print(responseObject)
                if responseObject.result.isSuccess {
                    let resJson = JSON(responseObject.result.value!)
                    //let title = resJson["title"].string
                    //print(title!)
                    success(resJson)
                }
    
                if responseObject.result.isFailure {
                    let error : Error = responseObject.result.error!
                    failure(error)
                }
            }
        }
    
        func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void){
            Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in
                //print(responseObject)
                if responseObject.result.isSuccess {
                    let resJson = JSON(responseObject.result.value!)
                    success(resJson)
                }
                if responseObject.result.isFailure {
                    let error : Error = responseObject.result.error!
                    failure(error)
                }
            }
        }
    }
    

    现在你可以调用 Singleton 类实例函数了

    AFWrapper.sharedInstance.requestPOSTURL(HttpsUrl.Address, params: dict as [String : AnyObject]?, headers: nil, success: { (json) in
        // success code
        print(json)
    }, failure: { (error) in
        //error code
        print(error)
    })
    

    【讨论】:

    • 对吗?实际上我第一次使用单例。并想知道为什么它更好?谢谢
    • 不客气。如果你觉得这很有用,请接受这个答案。以便其他人参考。
    • 我可以知道为什么单例更好请清除我的疑虑吗?谢谢
    • 这完全取决于您的需要。单例类和静态类各有利弊。请参考这个stackoverflow.com/questions/519520/…
    • 我们也可以使用静态类。这都是我们需要的。我只使用静态类。通过查看您的代码,我可以说您也可以使用静态类。
    【解决方案2】:

    也许你需要那个:

    import UIKit
    import Alamofire
    
    struct FV_API
    {
        //URL is http://www.stack.com/index.php/signup
        static let appBaseURL = ""  // assign your base url suppose:  http://www.stack.com/index.php
        static let apiSignUP = ""   // assign signup i.e: signup
    }
    
    class APIManager: NSObject
    {
        //MARK:- POST APIs
        class func postAPI(_ apiURl:String, parameters:NSDictionary, completionHandler: @escaping (_ Result:AnyObject?, _ Error:NSError?) -> Void)
        {
            var strURL:String = FV_API.appBaseURL  // it gives http://www.stack.com/index.php and apiURl is apiSignUP
    
            if((apiURl as NSString).length > 0)
            {
                strURL = strURL + "/" + apiURl    // this gives again http://www.stack.com/index.php/signup 
            }
    
            _ = ["Content-Type": "application/x-www-form-urlencoded"]
    
            print("URL -\(strURL),parameters - \(parameters)")
    
          let api =  Alamofire.request(strURL,method: .post, parameters: parameters as? [String : AnyObject], encoding: URLEncoding.default)
    
            // ParameterEncoding.URL
            api.responseJSON
                {
                    response -> Void in
    
                    print(response)
    
                    if let JSON = response.result.value
                    {
                        print("JSON: \(JSON)")
                        completionHandler(JSON as AnyObject?, nil)
                    }
                    else if let ERROR = response.result.error
                    {
                        print("Error: \(ERROR)")
                        completionHandler(nil, ERROR as NSError?)
                    }
                    else
                    {
                        completionHandler(nil, NSError(domain: "error", code: 117, userInfo: nil))
                    }
            }
        }
    

    在其他 NSObject 中,我使用了该方法,即用于注册:

    class SignUp: NSObject
    {
        class func registerWithAPI(firstName: String, lastName:String, completionHandler: @escaping (_ Result:AnyObject?, _ Error:NSError?) -> Void)
        {
            let dict = NSMutableDictionary()
    
            if !firstName.isEmpty
            {
               dict.setValue(firstName, forKey: "firstname")
            }
            if !lastName.isEmpty
            {
                dict.setValue(lastName, forKey: "lastname")
            }
    
            APIManager.postAPI(FV_API.apiSignUP, parameters: dict)
            {
                (Result, Error) -> Void in
                completionHandler(Result, Error)
            }
        }
    }
    

    在控制器类中,我创建了调用 api 的方法,例如:

    func apiForSignup()
        {
            SignUp.registerWithAPI(firstName: txtFieldFirstName.text!, lastName: txtFieldLastName.text!)
            {
                (Result, Error) -> Void in
                // write code
    }
    

    【讨论】:

    • 好的,让我检查一下。谢谢
    • 请检查我在哪里调用服务的更新问题。谢谢
    • 您能详细说明您的问题吗?在控制器中,您编写了 APIManager.apiPost() 但您的 NSObject 类名称是 AFWrapper。如果您使用我的答案,请按照所有步骤操作。
    • 我的问题是我没有收到回复。
    • 点击这里了解更多cocoacasts.com/…
    【解决方案3】:

    为 Swift 4 更新

    import UIKit
    import Alamofire
    import SwiftyJSON
    //
    // MARK:- ipv6 Configuration...
    //
    private var webView = UIWebView(frame: CGRect.zero)
    private var secretAgent: String? = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")
    var authHeaders: HTTPHeaders = ["User-Agent": secretAgent!, "Content-Type": "application/json; charset=utf-8"]
    
    class ApiManager: NSObject {
    
        static let sharedInstance = ApiManager()
    
        func requestGETURL(_ strURL: String, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void) {
    
            Alamofire.request(strURL).responseJSON { (responseObject) -> Void in
    
                if responseObject.result.isSuccess, let resJson = responseObject.result.value {
                    success(JSON(resJson))
                }
    
                if responseObject.result.isFailure {
                    let error : Error = responseObject.result.error!
                    failure(error)
                }
            }
        }
    
        func requestPOSTURL(_ strURL: String, params: [String : Any]?, headers: [String : String]?, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void) {
    
            Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: authHeaders).responseJSON { (responseObject) -> Void in
    
                if responseObject.result.isSuccess, let resJson = responseObject.result.value {
                    success(JSON(resJson))
                }
    
                if responseObject.result.isFailure {
                    let error : Error = responseObject.result.error!
                    failure(error)
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 2016-09-03
      • 2017-05-24
      • 2015-05-27
      • 1970-01-01
      • 2017-12-02
      • 2015-04-18
      相关资源
      最近更新 更多