使用swiftyJson和Alamofire作网络请求,以及json数据的解析

目的:使用Alamofire从网络请求json数据。用swiftyJson解析json数据,最后将须要的数据赋值给一个NSArray的数组。ios

1.下载swiftyJson 和 Alamofire(pods方式下载)git

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!

target 'issac-note' do
    #Networking
    pod "Alamofire"
    #pod "AlamofireObjectMapper"
    pod "SwiftyJSON"
    
end

2.在文件中引入:github

import UIKit
import Alamofire
import SwiftyJSON

3.网络请求,解析json,赋值NSArray:web

//初始化
var noteList: NSArray = []

//MARK: - getDataFormServer
    func getListDataFormServer() {
    
        let url = "http://issac.website/issac-noteBackstage/Admin/Index/getNotesByUid?uid=1"
        let parameters = ["uid":1]
    
        
        Alamofire.request(.POST, url, parameters: parameters).responseJSON { (response) in
            
            switch response.result {
            
            case .Success:
                
                //解析json数据
                let json = JSON(response.result.value!)
                
                //直接使用脚标的方式取出数组,先转化为arrayObject是重点,不转化是不能as 转化成?NSArray类型的
                self.noteList = json["data"].arrayObject! as NSArray
                //如果要赋值给一个NSDictionary,那就要先将转化成dictionaryObject
                
                //应为alamofire是异步请求,请求完成要刷新一下tableView才能才看数据
                self.tableView.reloadData()
                
            case .Failure:
                
                print("failure")
            
            }
            
        }
    
    }

请求回来的json数据:
 json

{
  "data" : [
    {
      "update_time" : "",
      "uid" : "1",
      "content" : "天天好一点,乐观一点,痛苦便没有那么清晰",
      "id" : "1",
      "status" : "1",
      "title" : "明日好起来",
      "create_time" : "1471941272"
    }
  ],
  "status" : 0,
  "msg" : "success"
}
相关文章
相关标签/搜索