簡體   English   中英

Swift:使用 Alamofire 和 SwiftyJSON 處理 JSON

[英]Swift: Handling JSON with Alamofire & SwiftyJSON

這個肯定要問好幾遍了,雖然我一直很努力地尋找,但我還沒有找到正確的答案。

我使用 Alamofire 和 SwiftyJSON,我的 JSON 數據如下所示:

{
  "528" : {
    "name" : "Name 1",
    "id" : "528",
    "product_id" : null,
    "visible" : "0",
    "level" : "2"
  },
  "29" : {
    "name" : "Name 2",
    "id" : "29",
    "product_id" : null,
    "visible" : "1",
    "level" : "1"
  },
  "173" : {
    "name" : "Name 3",
    "id" : "173",
    "product_id" : null,
    "visible" : "0",
    "level" : "2"
  },
  "143" : {
    "name" : "Name 4",
    "id" : "143",
    "product_id" : null,
    "visible" : "1",
    "level" : "2"
  },

...使用此代碼:

Alamofire.request(.GET, dataURL, parameters: nil, encoding: .JSON)

    .responseJSON { (request, response, jsonData, error) in

        let json = JSON(jsonData!) 

        println(json)

    }

...所以 JSON 一切都應該沒問題

  1. 我如何訪問這些數據? 我的意思是如何獲得姓名、ID、product_ids 等

  2. 我怎樣才能把數據(名稱)放到我的 TableViewController 中?

我在我的一個項目中同時使用 SwiftyJSON 和 Alamofire。 這是我如何使用它。

  1. 創建一個名為 APIProtocol 的協議。
  2. 使用接受 APIProtocol 類型委托的 GET 方法設置 API 類。
  3. 設置 TableViewController 以實現 APIProtocol。
  4. 從 TableViewController 調用 API.get()

代碼

// Step 1
protocol APIProtocol {
  func didReceiveResult(results: JSON)
}

// Step 2
func get(path: String, parameters: [String: AnyObject]? = nil, delegate: APIProtocol? = nil){
  let url = "\(self.hostname)\(path)"
  NSLog("Preparing for GET request to: \(url)")

  Alamofire.request(.GET, url, parameters: parameters)
    .responseJSON { (req, res, json, error) in
      if(error != nil) {
        NSLog("GET Error: \(error)")
        println(res)
      }
      else {
        var json = JSON(json!)
        NSLog("GET Result: \(json)")

        // Call delegate if it was passed into the call
        if(delegate != nil) {
            delegate!.didReceiveResult(json)
        }
      }
    }
}

// Step 3
class ActivityViewController: UITableViewController, APIProtocol {
  var activityModelList: NSMutableArray = [] // This is the array that my tableView is using.

  ... 

  func didReceiveResult(result: JSON) {
    var activities: NSMutableArray = []

    NSLog("Activity.didReceiveResult: \(result)")

    for (index: String, activity: JSON) in result {

      var activityModel = ActivityModel(
        id: activity["id"].intValue,
        message: activity["message"].stringValue
      )

      activities.addObject(activityModel)
    }

    // Set our array of new models
    activityModelList = activities

    // Make sure we are on the main thread, and update the UI.
    dispatch_sync(dispatch_get_main_queue(), {
      self.refreshControl!.endRefreshing()
      self.tableView.reloadData()
    })
  }
}

// Step 4
override func viewDidLoad() {
  MyAPI.get("/activities", delegate: self)
}

訪問器(至少對於 SwiftyJSON)的工作方式如下:

if let userName = json[0]["528"]["name"].string{
    println(userName) // "Name 1"
}

有關如何使用 SwiftyJSOn 的更多信息可以在其官方文檔中找到: https : //github.com/SwiftyJSON/SwiftyJSON

關於如何將數據放入 UITableView,有很多方法。 例如,設置一個 UITableView 單元格,然后以某種數組的形式加載 JSON 數據。

檢查此 repo 的示例,該示例聲明如何在代碼中使用 Alamofire 以及如何使用快速和解析 JSON 響應創建模型

  1. 在你的項目中安裝 Alamofire
  2. 在您的班級中導入 Alamofire
  3. 在你的類中定義這些變量

    typealias complitionBlock = (data: AnyObject) -> Void let KBASE_URL: String = "http://static.westwing.de/cms/dont-delete/programming_task/data.json"
  4. 設置此函數的實現

    func getMainItems(complition block: complitionBlock) { Alamofire.request(.GET, KBASE_URL, parameters:nil).responseJSON { response in do { let items = try NSJSONSerialization.JSONObjectWithData(response.data!, options: NSJSONReadingOptions()) as! NSArray let mutableArray: NSMutableArray = [] items.enumerateObjectsUsingBlock({ object, index, stop in let str = object as! NSDictionary //Replace WESItem with your model //let item = WESItem(dictionary: str as NSDictionary) mutableArray.addObject(item) }) block(data: mutableArray) } catch { print(error) } } }

更多信息: https : //github.com/AhmedAskar/WestWing

以下應該對你有用:-

           var nameArr = [String]() 

            Alamofire.request(.GET,"your url", parameters: nil)
                      .validate().responseJSON { response in
                         if let responseJson = response.result.value {
                           let name = responseJson["name"] as! String
                           nameArr.append(name)
                          }

                            dispatch_async(dispatch_get_main_queue(), {
                            self.tableView.reloadData()
                            })
                     }// Alamofire Close




 Use tableview as you normally use it i.e.

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")

        if cell == nil {
            cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
        }

        cell!.textLabel?.text = nameArr[indexPath.row]
        return cell!
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return nameArr.count
    }

注意:不需要使用 Swifty JSON,因為 Alamofire 允許 JSON 響應,可以在“.responseJSON”中直接處理。

pod 'Alamofire' pod 'SwiftyJSON' pod 'ReachabilitySwift'

import UIKit import Alamofire import SwiftyJSON import SystemConfiguration

class WebServiceHelper: NSObject {

typealias SuccessHandler = (JSON) -> Void
typealias FailureHandler = (Error) -> Void

// MARK: - Internet Connectivity

class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
            SCNetworkReachabilityCreateWithAddress(nil, $0)
        }
    }) else {
        return false
    }

    var flags: SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return false
    }

    let isReachable = flags.contains(.reachable)
    let needsConnection = flags.contains(.connectionRequired)

    return (isReachable && !needsConnection)
}

// MARK: - Helper Methods

class func getWebServiceCall(_ strURL : String, isShowLoader : Bool, success : @escaping SuccessHandler, failure : @escaping FailureHandler)
{
    if isConnectedToNetwork() {

        print(strURL)

        if isShowLoader == true {

            AppDelegate.getDelegate().showLoader()
        }

        Alamofire.request(strURL).responseJSON { (resObj) -> Void in

            print(resObj)

            if resObj.result.isSuccess {
                let resJson = JSON(resObj.result.value!)

                if isShowLoader == true {
                    AppDelegate.getDelegate().dismissLoader()
                }

                debugPrint(resJson)
                success(resJson)
            }
            if resObj.result.isFailure {
                let error : Error = resObj.result.error!

                if isShowLoader == true {
                    AppDelegate.getDelegate().dismissLoader()
                }
                debugPrint(error)
                failure(error)
            }
        }
    }else {


        CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
    }
}

class func getWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : @escaping SuccessHandler,  failure :@escaping FailureHandler){
    if isConnectedToNetwork() {

        if isShowLoader == true {
            AppDelegate.getDelegate().showLoader()
        }


        Alamofire.request(strURL, method: .get, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in

            print(resObj)

            if resObj.result.isSuccess {
                let resJson = JSON(resObj.result.value!)

                if isShowLoader == true {
                    AppDelegate.getDelegate().dismissLoader()
                }

                success(resJson)
            }
            if resObj.result.isFailure {
                let error : Error = resObj.result.error!

                if isShowLoader == true {
                    AppDelegate.getDelegate().dismissLoader()
                }

                failure(error)
            }

        })
    }
else {

        CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}

}



class func postWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : @escaping SuccessHandler, failure :@escaping FailureHandler)
{
    if isConnectedToNetwork()
    {

        if isShowLoader == true
        {
            AppDelegate.getDelegate().showLoader()
        }

        Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in

            print(resObj)

            if resObj.result.isSuccess
            {
                let resJson = JSON(resObj.result.value!)

                if isShowLoader == true
                {
                    AppDelegate.getDelegate().dismissLoader()
                }

                success(resJson)
            }

            if resObj.result.isFailure
            {
                let error : Error = resObj.result.error!

                if isShowLoader == true
                {
                    AppDelegate.getDelegate().dismissLoader()
                }

                failure(error)
            }
        })
    }else {
        CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
    }
}


class func postWebServiceCallWithImage(_ strURL : String, image : UIImage!, strImageParam : String, params : [String : AnyObject]?, isShowLoader : Bool, success : @escaping SuccessHandler, failure : @escaping FailureHandler)
{
    if isConnectedToNetwork() {
        if isShowLoader == true
        {
            AppDelegate.getDelegate().showLoader()
        }

        Alamofire.upload(
            multipartFormData: { multipartFormData in
                if let imageData = UIImageJPEGRepresentation(image, 0.5) {
                    multipartFormData.append(imageData, withName: "Image.jpg")
                }

                for (key, value) in params! {

                    let data = value as! String

                    multipartFormData.append(data.data(using: String.Encoding.utf8)!, withName: key)
                    print(multipartFormData)
                }
            },
            to: strURL,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        debugPrint(response)
                        //let datastring = String(data: response, encoding: String.Encoding.utf8)
                       // print(datastring)
                    }
                case .failure(let encodingError):
                    print(encodingError)
                    if isShowLoader == true
                    {
                        AppDelegate.getDelegate().dismissLoader()
                    }

                    let error : NSError = encodingError as NSError
                    failure(error)
                }

                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { (response) -> Void in

                        if response.result.isSuccess
                        {
                            let resJson = JSON(response.result.value!)

                            if isShowLoader == true
                            {
                                AppDelegate.getDelegate().dismissLoader()
                            }

                            success(resJson)
                        }

                        if response.result.isFailure
                        {
                            let error : Error = response.result.error! as Error

                            if isShowLoader == true
                            {
                                AppDelegate.getDelegate().dismissLoader()
                            }

                            failure(error)
                        }

                    }
                case .failure(let encodingError):
                    if isShowLoader == true
                    {
                        AppDelegate.getDelegate().dismissLoader()
                    }

                    let error : NSError = encodingError as NSError
                    failure(error)
                }
            }
        )
    }
    else
    {
        CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
    }
}
}

================================== 

調用方法

讓 aParams : [String : String] = ["DeviceIDString", "DeviceType" : "iOS", ]

        WebServiceHelper.postWebServiceCall(Constants.BaseURL, params: aParams as [String : AnyObject]?, isShowLoader: true, success: { (responceObj) in


            if "\(responceObj["RespCode"])" != "1"
            {
                let alert = UIAlertController(title: Constants.kAppName, message: "\(responceObj["RespMsg"])", preferredStyle: UIAlertControllerStyle.alert)
                let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
                }
                alert.addAction(OKAction)
                self.present(alert, animated: true, completion: nil)
            }
            else
            {
                let aParams : [String : String] = [
                    "Password" : self.dictAddLogin[AddLoginConstants.kPassword]!,
                    ]
                CommonMethods.saveCustomObject(aParams as AnyObject?, key: Constants.kLoginData)

            }
            }, failure:
            { (error) in

                CommonMethods.showAlertWithError(Constants.kALERT_TITLE_Error, strMessage: error.localizedDescription,withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
        })
    }

// 使用 alamofire 獲取 json 數據 swiftjson

// 首先使用 Alamofire

//第二個在tableView中的fatch json數據

// 創建json模型類model1

// MODEL2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM