如何用Alamofire发布SwiftyJSON?

时间:2017-07-19 04:26:37

标签: ios json alamofire swifty-json

我想通过Alamofire发布JSON。

但我不太确定如何处理它。

我的swiftyJSON在数组中作为我的

如何将JSON数组编码为dictionaryObject?适合

Alamofire's Parameters?

urlRequest = try JSONEncoding.default.encode(urlRequest, with: location)

我的示例JSON如下所示:

"[{\n    acc = accuracy;\n    lat = lat;\n    long = long;\n    type = type;\n}, {\n    acc = accuracy;\n    lat = lat;\n    long = long;\n    type = type;\n}, {\n    acc = accuracy;\n    lat = lat;\n    long = long;\n    type = type;\n}, {\n    acc = accuracy;\n    lat = lat;\n    long = long;\n    type = type;\n}, {\n    acc = accuracy;\n    lat = lat;\n    long = long;\n    type = type;\n}]"

4 个答案:

答案 0 :(得分:0)

First add SwiftJSON to your project then 
class func requestPOSTURL(serviceName:String,parameters: [String:Any]?, completionHandler: @escaping (JSON?, NSError?) -> ()) {

        let headersSet: HTTPHeaders = [
            "Authorization":GlobalAccesstoken,
            "Accept": "application/json"
        ]
        Alamofire.request(serviceName, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headersSet).responseJSON {
            (response:DataResponse<Any>) in
            switch(response.result) {
            case .success(_):
                if let data = response.result.value{
                    let json = JSON(data)
                    completionHandler(json,nil)
                }
                break
            case .failure(_):
                completionHandler(nil,response.result.error as NSError?)

                break
            }
        }
    }

AFWrapper.requestPOSTURL(serviceName: LapiUrl+"get_profile", parameters: params) { (response:JSON?, error:NSError?) in
            if error != nil {
                print(error!)
return
            }
if response == nil {
return
            }
 print(response!)
            var distRespoce  = response!.dictionary?["response"]?.array?[0]
 if (distRespoce?["status"].string == "true"){

                let distuserData = distRespoce!.dictionary?["user_data"]
}
            else{
                print("no")
            }
}

Try above code ..

答案 1 :(得分:0)

你可以这样做: -

        Alamofire.request(urlString, method: .post, parameters: paramData, encoding:JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
            switch(response.result)
            {
            case .success(_):

                if response.result.value != nil
                {
                    do
                    {
                        var dict : NSDictionary = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                        print(dict)
                        dict = UtilityClass.removeNullFromResponse(response: response.result.value! as! NSDictionary)
                        self.dataBlock(dict,nil)
                    }
                    catch
                    {
                        UtilityClass.hideHudLoading()
                    }
                }
                break

            case .failure(_):
                if response.result.error != nil
                {
                    print(response.result.error!)
                    UtilityClass.hideHudLoading()
                }
                break
            }
        }
    }

答案 2 :(得分:0)

诀窍是你需要将它转换为字典。 示例摘录如下:

```

    // let assume swiftyJSON is a SwiftyJSON object (JSON)
    if let data = swiftyJSON.rawString()!.data(using: .utf8) {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
            Alamofire.request(url, method: .post, parameters: json, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
                debugPrint(response)
            }                  
        } catch {
            print("JSONSerialization error")
        }
    }          

```

答案 3 :(得分:0)

  

简单获取邮政编码,易于使用,维护和理解

下面是pod,您必须使用我的json解析代码。

#Network manager related
pod 'Alamofire',                            :git => 'https://github.com/Alamofire/Alamofire.git', :tag => ‘4.0.1’
pod 'AlamofireNetworkActivityIndicator',    '~> 2.0'
pod 'AlamofireObjectMapper',                '~> 4.0.0'
pod 'SVProgressHUD',                        :git => 'https://github.com/SVProgressHUD/SVProgressHUD.git'
pod 'Reachability',                         '~> 3.2'
pod 'SwiftyJSON',                           '~> 3.0.0'
pod 'ObjectMapper',                        '~> 2.0'
pod 'SDWebImage',                           '~> 3.8'

在这里,您可以在视图控制器中调用API。

RegistrationService().login(email: (txtEmail.text)!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines), password: self.txtPassword.text!, success: { (response) in
        //Save data to user default
    }) { (error) in
        print(error as Any)
    }

RegistrationService.swift //服务类,您可以在其中添加api&#39;

//
//  RegistrationService.swift
//  hotelBids
//
//  Created by Mehul Parmar on 27/05/16.
//  Copyright © 2017 Sooryen Innovation labs. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON
import ObjectMapper
import AlamofireObjectMapper

open class RegistrationService {

    enum listOfApi : String {
        case
        login,
        country
    }


 func country(_ success:@escaping (_ responseObject:JSON) -> Void , failure:@escaping (_ errorResponse:JSON?) -> Void) {

        // create post request
        NetworkManager().Get(listOfApi.country.rawValue,
                              paramaters: [:],
                              showLoader: true,
                              success: { responseObject in
                                success(responseObject)
        }) { error in
            failure(error)
        }
    }

    func login(email: String, password: String, success:@escaping (_ responseObject:JSON) -> Void , failure:@escaping (_ errorResponse:JSON?) -> Void) {

        // create request parameter
        let requestParameters = ["email"        :   email,
                                 "password"     :   password,
                                 "user_role"    :   "customer"
        ]

        // create post request
        NetworkManager().POST(listOfApi.login.rawValue,
                              paramaters: requestParameters as [String : AnyObject]?,
                              showLoader: true,
                              success: { responseObject in
                                success(responseObject)
        }) { error in
            failure(error)
        }
    }

<强> NetworkManager.swift

//
//  NetworkManager.swift
//  Constants.kAppName.localized()
//
//  Created by Mehul Parmar on 08/06/16.
//  Copyright © 2016 . All rights reserved.
//

import Foundation
import Alamofire
import SVProgressHUD
import SwiftyJSON
//import AMSmoothAlert
import ObjectMapper
import AlamofireObjectMapper

//used for facebook logour while invalid session
import FacebookLogin

//MARK : - Errors
enum NetworkConnection {
  case available
  case notAvailable
}

class NetworkManager {
    let baseUrlDev_OLD : String = "https://hotelbids.com/" + "dev/" + "hb-app/" +  "v3/" + "user/"
    let baseUrlDev : String = "http://184.73.131.211/api/v1/"

    //MARK : - Shared Manager
    let sharedManager = SessionManager()

    func getHeaders(_ urlString: String) -> [String: String] {

        var headerDictionary = [String: String]()

        if UserDetail.rememberToken != nil {
            if (UserDetail.rememberToken?.length)! > 0 {
                headerDictionary[Constants.KEY_remember_token] = "\(UserDetail.rememberToken!)"
            }
        }

        /*
        if let xapi = UserDefault.getXapi() {
            headerDictionary[Constants.KEY_Xapi] = xapi
        }

        if let accessLanguage = UserDefault.getLanguage() {
            headerDictionary[Constants.KEY_Language] = accessLanguage
        }

        if let userId = UserDefault.getUserId() {
            headerDictionary[Constants.KEY_USER_ID] = userId
        }

        if let accessToken = UserDefault.getAccessToken() {
            headerDictionary[Constants.KEY_AccessToken] = accessToken
        }*/

        print("urlString: \(urlString)\nheaderDictionary : \(headerDictionary)")
        return headerDictionary
    }

    func printResponse(urlString: String, paramaters: [String: AnyObject]?, response: AnyObject) {

        let dictResponce = self.getValidatedData(response as AnyObject)

//        if dictResponce.boolValue {
            if let paramatersTemp = paramaters {
                if paramatersTemp.values.count > 0 {
                    let jsonParameters = JSON(paramatersTemp)
                    print("\n\n\nurlString : \(urlString) ,\n\n paramaters: \(jsonParameters) ,\n\n Response: \(String(describing: dictResponce))\n\n\n")
                }
                else {
                    print("\n\n\nurlString : \(urlString) ,\n\n Response: \(String(describing: dictResponce))\n\n\n")
                }
            }
            else {
                print("\n\n\nurlString : \(urlString) ,\n\n Response: \(String(describing: dictResponce))\n\n\n")
            }
//        } else {
//            print("urlString : \(urlString) ,\n Response: \(String(describing: dictResponce))")
//        }
    }

    func getValidatedData(_ response: AnyObject?) -> JSON {

        //Removing null and <null>, and replacing number or integer to string
        guard var dictResponse = response as? NSDictionary else{
            return nil
        }

        dictResponse = (dictResponse.replacingNullsWithStrings() as NSDictionary).convertingNumbersToStrings()! as NSDictionary
        let jsonResponce = JSON(dictResponse)
        return jsonResponce
    }

    // MARK: - Get Method
    func Get(_ urlString: String, paramaters: [String: AnyObject]? = nil, showLoader: Bool? = nil, success:@escaping (_ responseObject:JSON) -> Void , failure:@escaping (_ errorResponse:JSON?) -> Void) {

        switch checkInternetConnection() {
        case .available:
            if let showLoader = showLoader {
                if showLoader {
                    DispatchQueue.main.async {
                        // update some UI
                        UIApplication.shared.keyWindow?.showLoader()
                    }
                }
            }

            Alamofire.request(baseUrlDev.add(urlString: urlString), method: .get, parameters: paramaters, encoding: URLEncoding.default, headers: self.getHeaders(urlString)).responseJSON (completionHandler: { response in

                DispatchQueue.main.async {
                    if UIApplication.shared.isIgnoringInteractionEvents {
                        UIApplication.shared.endIgnoringInteractionEvents()
                    }

                    if let showLoader = showLoader {
                        if showLoader {
                            if SVProgressHUD.isVisible() {
                                SVProgressHUD.dismiss()
                            }
                        }
                    }
                }

                //Success
                if response.result.isSuccess {
                    if let value = response.result.value {
                        let dictResponce = self.isValidated(value as AnyObject)

                        //Print response using below method
                        self.printResponse(urlString: urlString, paramaters: paramaters, response: (value as AnyObject))

                        if dictResponce.0 == true {
                            success(dictResponce.1)
                        }
                        else {
                            failure(dictResponce.1)
                        }
                    }
                }
                else {
                    //Check response error using status code
                    if let strErrorReasonCode : Int = response.response?.statusCode {

                        if let data = response.data {
                            let jsonResponce = JSON(data: data)
                            if strErrorReasonCode == 500 {
                                print("\n\n\n\n server error :\(AppAlertMsg.kErrorMsg) \n\n URL:\(urlString) \n\n paramaters:\(JSON(paramaters as Any))\n\n\n\n")
                                UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kErrorMsg, duration: 3.0, position: "bottom" as AnyObject)
                                failure(jsonResponce)
                                return
                            }

                            if let dictionary : NSDictionary = jsonResponce.dictionaryObject as NSDictionary? {
                                let responce : ResponseDataModel = ModelManager.sharedInstance.getResponseDataModel(dictionary)
                                let authentication_Errors = 401
                                let authentication_Errors_Range = 400..<500
                                let Alamofire_Error = -1005

                                if authentication_Errors == strErrorReasonCode {
                                    print("\n\n\n\nauthentication_Errors :\(strErrorReasonCode) \n\nmessage: \(responce.message) \n\nparamaters: \(String(describing: paramaters)) \n\nresponse: \(jsonResponce)\n\n\n\n")
                                    self.isUnAuthotized()
                                    failure(jsonResponce)
                                }
                                else if authentication_Errors_Range.contains(strErrorReasonCode) {
                                    print("\n\n\n\nauthentication_Errors_Range :\(strErrorReasonCode) \n\nmessage: \(responce.message) \n\nparamaters: \(String(describing: paramaters)) \n\nresponse: \(jsonResponce)\n\n\n\n")
                                    CustomAlert().ShowAlert(responce.message)
                                    failure(jsonResponce)
                                }
                                else if authentication_Errors_Range.contains(Alamofire_Error) {
                                    self.POST(urlString, paramaters: paramaters, showLoader: showLoader, success: { (responseObject) in
                                        if response.result.isSuccess {
                                            if let value = response.result.value {
                                                let dictResponce = self.isValidated(value as AnyObject)
                                                if dictResponce.0 == true {
                                                    success(dictResponce.1)
                                                }
                                                else {
                                                    failure(dictResponce.1)
                                                }
                                            }
                                        }
                                    }, failure: {_ in
                                        failure(jsonResponce)
                                    })
                                }
                            }
                            else {
                                print("\n\n\n\n server error :\(AppAlertMsg.kErrorMsg) \n\n URL:\(urlString) \n\n paramaters:\(JSON(paramaters as Any))\n\n\n\n")
                                UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kErrorMsg, duration: 3.0, position: "bottom" as AnyObject)
                                failure(jsonResponce)
                            }
                        }
                    }
                    else {
                        failure(nil)
                    }
                }
            })

        case .notAvailable:
            if let _ = showLoader {
                UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kNoInternet, duration: 3.0, position: "bottom" as AnyObject)
            }
            failure(JSON(AppAlertMsg.kNoInternet))
            print("No internet")
        }
    }

    // MARK: - POST Method
    func POST(_ urlString: String, paramaters: [String: AnyObject]? = nil, showLoader: Bool? = nil, success:@escaping (_ responseObject:JSON) -> Void , failure:@escaping (_ errorResponse:JSON?) -> Void) {

        switch checkInternetConnection() {
        case .available:
            if let showLoader = showLoader {
                if showLoader {
                    DispatchQueue.main.async(execute: {
                        if !UIApplication.shared.isIgnoringInteractionEvents {
                            UIApplication.shared.beginIgnoringInteractionEvents()
                        }
                        SVProgressHUD.show(withStatus: AppAlertMsg.kPleaseWait)
                    })
                }
            }

            sharedManager.request(baseUrlDev.add(urlString: urlString), method: .post, parameters: paramaters, encoding: JSONEncoding.default, headers: self.getHeaders(urlString)).validate().responseJSON(completionHandler: { response in


                DispatchQueue.main.async {
                    if UIApplication.shared.isIgnoringInteractionEvents {
                        UIApplication.shared.endIgnoringInteractionEvents()
                    }

                    if let showLoader = showLoader {
                        if showLoader {
                            if SVProgressHUD.isVisible() {
                                SVProgressHUD.dismiss()
                            }
                        }
                    }
                }

                //Success
                if response.result.isSuccess {
                    if let value = response.result.value {

                        let dictResponce = self.isValidated(value as AnyObject)

                        //Print response using below method
                        self.printResponse(urlString: urlString, paramaters: paramaters, response: (value as AnyObject))

                        if dictResponce.0 == true {
                            success(dictResponce.1)
                        }
                        else {
                            failure(dictResponce.1)
                        }
                    }
                } else {
                    //Check response error using status code
                    if let strErrorReasonCode : Int = response.response?.statusCode {
                        if let data = response.data {
                            let jsonResponce = JSON(data: data)
                            if strErrorReasonCode == 500 {
                                print("\n\n\n\n server error :\(AppAlertMsg.kErrorMsg) \n\n URL:\(urlString) \n\n paramaters:\(JSON(paramaters as Any))\n\n\n\n")
                                UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kErrorMsg, duration: 3.0, position: "bottom" as AnyObject)
                                failure(jsonResponce)
                                return
                            }


                            if let dictionary : NSDictionary = jsonResponce.dictionaryObject as NSDictionary? {
                                let responce : ResponseDataModel = ModelManager.sharedInstance.getResponseDataModel(dictionary)
                                let authentication_Errors = 401
                                let authentication_Errors_Range = 400..<500
                                let Alamofire_Error = -1005

                                if authentication_Errors == strErrorReasonCode {
                                    print("\n\n\n\nauthentication_Errors (jsonResponce)\n\n\n\n")
                                    self.isUnAuthotized()
                                    failure(jsonResponce)
                                }
                                else if authentication_Errors_Range.contains(strErrorReasonCode) {
                                    print("\n\n\n\nauthentication_Errors_Range :\(strErrorReasonCode) \n\nmessage: \(responce.message) \n\nparamaters: \(String(describing: paramaters)) \n\nresponse: \(jsonResponce)\n\n\n\n")
                                    CustomAlert().ShowAlert(responce.message)
                                    failure(jsonResponce)
                                }
                                else if authentication_Errors_Range.contains(Alamofire_Error) {
                                    self.POST(urlString, paramaters: paramaters, showLoader: showLoader, success: { (responseObject) in
                                        if response.result.isSuccess {
                                            if let value = response.result.value {
                                                let dictResponce = self.isValidated(value as AnyObject)
                                                if dictResponce.0 == true {
                                                    success(dictResponce.1)
                                                }
                                                else {
                                                    failure(dictResponce.1)
                                                }
                                            }
                                        }
                                    }, failure: {_ in
                                        failure(jsonResponce)
                                    })
                                }
                            }
                            else {
                                print("\n\n\n\n server error :\(AppAlertMsg.kErrorMsg) \n\n URL:\(urlString) \n\n paramaters:\(JSON(paramaters as Any))\n\n\n\n")
                                UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kErrorMsg, duration: 3.0, position: "bottom" as AnyObject)
                                failure(jsonResponce)
                            }
                        }
                    }
                    else {
                        failure(nil)
                    }
                }
            })

        case .notAvailable:
            if let _ = showLoader {
                UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kNoInternet, duration: 3.0, position: "bottom" as AnyObject)
            }
            failure(JSON(AppAlertMsg.kNoInternet))
            print("No internet")
        }
    }


    // MARK: - No Internet Connection
    func checkInternetConnection() -> NetworkConnection {

        if isNetworkAvailable() {
            return .available
        }
        return .notAvailable
    }

    // MARK: - Check Status
    func isValidated(_ response: AnyObject?) -> (Bool, JSON) {

        //Removing null and <null>, and replacing number or integer to string
        guard var dictResponse = response as? NSDictionary else{
            return (false,nil)
        }

        dictResponse = (dictResponse.replacingNullsWithStrings() as NSDictionary).convertingNumbersToStrings()! as NSDictionary
        let jsonResponce = JSON(dictResponse)
        let responseModel : ResponseDataModel = ModelManager.sharedInstance.getResponseDataModel(dictResponse)

        /* //
         HTTP Status Code

         200 –   Success/OK
         4xx –   Authentication Errors
         5xx –   Service  Errors
         */ //


        guard let statusCodeInt = responseModel.code.toInt() else {
            print("code is not proper")
            return (false,jsonResponce)
        }

        let success_Range = 200..<300
        let authentication_Errors = 401
        let authentication_Errors_Range = 400..<500
        let service_Errors_Range = 500..<600

        if success_Range.contains(statusCodeInt) {
            // all okey
            return (true, jsonResponce)
        }
        else if authentication_Errors == statusCodeInt {
            print("service_Errors_Range :\(statusCodeInt)")
            self.isUnAuthotized()
            return (false,jsonResponce)
        }
        else if authentication_Errors_Range.contains(statusCodeInt) {
            print("authentication_Errors_Range :\(statusCodeInt)")
            CustomAlert().ShowAlert(responseModel.message)
            return (false,jsonResponce)
        }
        else if service_Errors_Range.contains(statusCodeInt) {
            print("service_Errors_Range :\(statusCodeInt)")
            CustomAlert().ShowAlert(responseModel.message)
            return (false,jsonResponce)
        }
        else {
            return (false,nil)
        }
    }

    func isUnAuthotized() {
        // we have to logout, bcos session expired , or user unauthorized
        CustomAlert().ShowAlert(isCancelButton: false, strMessage: AppAlertMsg.kUnAuthotized) { (isYESClicked) in
            if isYESClicked {
                //Delete all data from  user default
                //Set sign in as Home screen
                print("set to Login view controller ")

                GmailClass.sharedInstance().signOut()
                LoginManager().logOut()

                UserStatus = UserType.Fresh.rawValue

                let deviceTokenTemp = DeviceToken
                if let bundle = Bundle.main.bundleIdentifier {
                    UserDefaults.standard.removePersistentDomain(forName: bundle)
                }
                DeviceToken = deviceTokenTemp

                Constants.appDelegate.logoutSuccess()
            }
        }
    }

    // MARK: - Loader method
    class func ShowActivityIndicatorInStatusBar() {

        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }

    class func HideActivityIndicatorInStatusBar() {

        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    }
}

extension String {
    func add(urlString: String) -> URL {
        return URL(string: self + urlString)!
    }

    func EncodingText() -> Data {
        return self.data(using: String.Encoding.utf8, allowLossyConversion: false)!
    }
}