前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【swift学习笔记】四.swift使用Alamofire和swiftyJson

【swift学习笔记】四.swift使用Alamofire和swiftyJson

作者头像
lpxxn
发布2018-01-31 13:56:16
1.9K0
发布2018-01-31 13:56:16
举报
文章被收录于专栏:技术之路

  Alamofire是AFNetworking的swift版本,功能灰常强大。

github:https://github.com/Alamofire/Alamofire

  SwiftyJSON是操作json的非常棒的开源库

github:https://github.com/SwiftyJSON/SwiftyJSON

  接下来我做一个简单的入门小例子,

  我使用cocoaPods来管理依赖,需要在Podfile里添加我们需要的两个库

代码语言:javascript
复制
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!

target 'AlamofireDemo' do
  pod 'Alamofire', '~> 3.4'
  pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
end

在terminal里运行

 cocoapods会为我们自动生成需要导入的第三方库的信息。

关闭工程打开cocoaPods为我们生成的工程文件,编辑通过后就能导入这两个库了

代码语言:javascript
复制
import Alamofire
import SwiftyJSON

因为我们要访问网络,需要在info.plist里开放权限,加入下面的代码

代码语言:javascript
复制
 <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

接下来就可以用它Alamofire请求网络使用swiftyJson解析Json

代码语言:javascript
复制
let currRequest = Alamofire.request(.POST, "http://www.yourweb.com", parameters: ["para1":"aaa",
            "para2":[0,1,2,3],
            "para3":NSNull()],
            encoding: .JSON, headers: ["Content-Type":"application/json"])
       
        currRequest.responseJSON{(responseJson) -> Void in
            print(responseJson.response?.statusCode)
            print(responseJson.request)
            print(responseJson.response)
            print(responseJson.data)
            print(responseJson.result)
            
            switch responseJson.result {
            case .Success(let value):
                print("Value:\(value)")
                print("------")
                let swiftyJsonVar = JSON(value)
                print(swiftyJsonVar)
                
            case .Failure(let error):
                print(error)
            }
        }

好了这个简单的例子就写完了,还有一个更方便的方法就是用下边这个库,他是集成了上边说的两个库,有时间你可以玩一下

https://github.com/SwiftyJSON/Alamofire-SwiftyJSON

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-06-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档