如何使用Swift 3在Alamofire上使用singleton?

问题描述 投票:1回答:3

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

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

下面是我的包装类代码:

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
3个回答
6
投票

我没有仔细研究你的代码。在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)
})

1
投票

可能你需要那个:

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
}

0
投票

针对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)
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.