IOS中Alamofire第三方网络框架的基本用法(总结)

步骤1

安装CoCoaPods类库管理工具:

方法:打开终端,输入命令:sudo gem install cocoapods即可自动进行安装。安装完成后,可以输入命令:pod --version查看Pod版本。

步骤2

(1)创建Podfile文件:

方法:在终端cd到项目目录下,运行命令:pod init即可自动创建该文件。

(2)修改Podfile文件:

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'AlamofireDemo' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

pod'Alamofire','~>4.7'

  # Pods for AlamofireDemo

  target 'AlamofireDemoTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'AlamofireDemoUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end


(3)安装Alamofire第三方开源类库

方法:在终端cd到项目目录下,运行命令:pod install即可自动安装相应的类库。

步骤3

如何使用?

import UIKit
import Alamofire

class ViewController: UIViewController {

    var urlStringGet = "https://httpbin.org/get";
    var urlStringPost = "https://httpbin.org/post";
    var urlStringupload = "https://httpbin.org/post";
    var urlStringDownload = "https://httpbin.org/image/png";
    
    var imageView:UIImageView!;
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        imageView = UIImageView();
        imageView.image = UIImage(named: "landscape_1");
        imageView.frame = CGRect(x: 0, y: 50, width: 100, height: 100);
        
        self.view.addSubview(imageView);
        
        //getHandler();
        //postHandler();
        //uploadHandler();
        downloadHandler(fileName: "pig.jpg")
    }
    
    //GET方式
    func getHandler() {
        DispatchQueue.main.async(execute: {() in
            Alamofire.request(self.urlStringGet).responseJSON{response in
                if let json = response.result.value {
                    print("JSON\(json)");
                }
            }
        })
        
    }
    
    //POST方式
    func postHandler() {
        var parameters: Parameters;
        parameters = ["foo":"bar", "baz":["a", 1], "qux":["x":1, "y":2, "z":3]];
        
        DispatchQueue.main.async(execute: {() in
            Alamofire.request(self.urlStringPost, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { response in
                if let json = response.result.value {
                    print("JSON\(json)");
                }
            }

        })
    }
    
    //上传文件
    func uploadHandler() {
        let fileURL = Bundle.main.url(forResource: "landscape_1", withExtension: "jpg");
        DispatchQueue.main.async(execute: {() in
            Alamofire.upload(fileURL!, to: self.urlStringupload)
                .uploadProgress { progress in
                    print("上传进度:\(progress.fractionCompleted)");
                    print("已上传:\(progress.completedUnitCount)");
                    print("总大小:\(progress.totalUnitCount)")
                }
                .responseJSON {response in
                print(response.result);
            }
        })
    }
    
    //文件下载
    func downloadHandler(fileName:String) {
        let destination: DownloadRequest.DownloadFileDestination = {_, _ in
            let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0];
            let fileURL = documentURL.appendingPathComponent(fileName);
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories]);
        }
        DispatchQueue.main.async(execute: {() in
            Alamofire.download(self.urlStringDownload, to: destination)
                .downloadProgress { progress in
                    print("下载进度:\(progress.fractionCompleted)");
                    print("已下载:\(progress.completedUnitCount)");
                    print("总大小:\(progress.totalUnitCount)")
            }
                .responseData {response in
                    if let data = response.result.value {
                        let image = UIImage(data: data);
                        self.imageView.image = image;
                    }
                    
            }
        })
    }


}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值