微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Swift通天遁地]四、网络和线程-(4)使用Alamofire实现网络请求

本文将演示如何使用第三方库实现网络请求服务。

首先确保在项目中已经安装了所需的第三方库。

点击【Podfile】,查看安装配置文件

1 source https://github.com/CocoaPods/Specs.git
2 platform :ios,12.0
3 use_frameworks!
4 
5 target ‘DemoApp’ do
6     pod Alamofire,~> 4.0
7 end

根据配置文件中的相关配置,安装第三方库。

然后点击打开【DemoApp.xcworkspace】项目文件

在项目导航区,打开视图控制器的代码文件【ViewController.swift】

现在开始编写代码,访问一个网络接口,并在控制台输出返回的信息。

 1 import UIKit
 2 //在当前的类文件中,引入已经安装的第三方类库
 3 import Alamofire
 4 
 5 class ViewController: UIViewController {
 6 
 7     override func viewDidLoad() {
 8         super.viewDidLoad()
 9         // Do any additional setup after loading the view,typically from a nib.
10         
11         //调用网络操作库的网络请求方法,并处理从服务器返回的JSON信息
12         Alamofire.request("https://httpbin.org/get").responseJSON { response in
13             
14             //在控制台输出:返回的网络请求对象
15             print("response.request:\(response.request)")
16             //在控制台输出:网络返回对象
17             print("response.response:\(response.response)")
18             //在控制台输出:由服务器返回的数据
19             print("response.data:\(response.data)")
20             //在控制台输出:返回对象序列化后的结果
21             print("response.result:\(response.result)")
22             
23             //输出结果的值
24             if let JSON = response.result.value
25             {
26                 print("JSON: \(JSON)")
27             }
28         }
29     }
30 
31     override func didReceiveMemoryWarning() {
32         super.didReceiveMemoryWarning()
33         // dispose of any resources that can be recreated.
34     }
35 }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐