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

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

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

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.在文件中引入:

import UIKit
import Alamofire
import SwiftyJSON

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

//初始化
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数据:
 

{
  "data" : [
    {
      "update_time" : "",
      "uid" : "1",
      "content" : "每天好一点,乐观一点,痛苦便没有那么清晰",
      "id" : "1",
      "status" : "1",
      "title" : "明日好起来",
      "create_time" : "1471941272"
    }
  ],
  "status" : 0,
  "msg" : "success"
}

 

转载于:https://my.oschina.net/u/2487410/blog/742580

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值