[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 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10222294.html