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

简介:

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

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

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

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

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

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

复制代码
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为我们生成的工程文件,编辑通过后就能导入这两个库了

import Alamofire
import SwiftyJSON

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

 <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

 

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

 

复制代码
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

 

本文转自lpxxn博客园博客,原文链接:http://www.cnblogs.com/li-peng/p/5558551.html,如需转载请自行联系原作者


相关文章
|
Swift 数据安全/隐私保护 iOS开发
iOS开发 - swift通过Alamofire实现https通信
iOS开发 - swift通过Alamofire实现https通信
343 0
iOS开发 - swift通过Alamofire实现https通信
|
Swift
Swift - Alamofire简单GET和POST使用
Swift - Alamofire简单GET和POST使用
306 0
|
Swift
Swift - 不使用pods如何正确添加类似Alamofire这样的库
Swift - 不使用pods如何正确添加类似Alamofire这样的库
103 0
Swift - 不使用pods如何正确添加类似Alamofire这样的库
|
Swift
Swift学习笔记——页面跳转
创建一个single view app后,项目中有main.storyboard,里面是一个viewcontroller。 那么我们如何实现页面跳转 首先添加一个导航控制器Navigation Controller。点击右上的➕,然后选择控件拖到面板上即可
1150 0
|
前端开发 测试技术 Swift
Swift学习笔记——新建项目
在xcode菜单中选择 new -> project -> single view app 点击next在弹出窗中填写项目名称 这里languge有可以选择object-c或swift作为项目语言。这里我们学习swift,所以选择swift。 如果language选择swift,下面的user interface可以选择swiftUI和storyboard。 SwiftUI是2019 年 WWDC 大会上,苹果在压轴环节向大众宣布了基于 Swift 语言构建的全新 UI 框架,与flutter类似,是用代码编写页面,支持快速预览。
664 0

相关课程

更多