Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了[快速学会Swift第三方库] Alamofire篇大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

[快速学会Swift第三方库] Alamofire篇 Alamofire是 Swift 语言的 http 网络开发工具包,AFNetworking的 Swift 版,使用起来相当简单。 目录 快速学会Swift第三方库 Alamofire篇 目录 编码之前 导入Alamofire 其他操作 Web请求 示例代码 运行结果 数据请求JSON 示例代码 运行结果 上传文件 示例代码 运行结果 下载文件

[@L_262_0@学会Swift第三方库] Alamofire篇

Alamofire是 Swift 语言的 http 网络开发工具包,AFNetworking的 Swift 版,使用起来相当简单。

目录

编码之前

导入Alamofire

推荐使用COcoaPods进行导入,CocoaPods是一个负责管理iOS项目中第三方开源库的工具,安装CocoaPods之后使用命令行就能轻松地对所有第三方开源库进行安装和更新,而不需要每次上GitHub去下载。
CocoaPods的安装过程传送门:iOS 9 导入类库全面详尽过程(Ruby安装->CocoaPods安装->导入类库)
手动下载:GitHub-Alamofire 主页

装好CocoaPods后,修改Podfile文件内容为如下:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios,'9.0'
use_frameworks!

target 'Web' do
pod 'Alamofire','~> 3.4'
end
xcodeproj 'Desktop/Web/Web.xcodeproj'

target后面为工程名,最后一行为工程路径(这里的Web是我的工程名)

再执行命令:

$ pod install

其他操作

另外还需要在Target->工程名->Build SetTings->Search Paths->User Header Search Paths处添加Alamofire所在的目录:

最后在你需要用到Alamofire的类中加上

import Alamofire

Web请求

示例代码

func webrequst() {
        Alamofire.request(.GET,"http://blog.csdn.net/sps900608",parameters: nil)
                 .responseData { (responsE) in
                     print("webrequest:\(response.result)")
                     //注意:webView需自定义!
                     self.webView.loadData(response.result.value!,MIMEType: "text/html",textEncodingName: "utf-8",baseURL: NSURL())
                 }
    }

运行结果:

webrequest:succesS

数据请求(JSON)

示例代码

func jsonrequest()  {
        let parameters = [ "foo": "bar","baz": ["a",1],"qux": ["x": 1,"y": 2,"z": 3]]

        // http body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
        Alamofire.request(.POST,"https://httpbin.org/post",parameters: parameters)
                 .responseJSON { (responsE) in
                     print("jsonrequest:\(response.result)")

                     if let JSON = response.result.value {
                            print("JSON: \(JSON)")
                     }
        }
    }

运行结果

@H_772_214@jsonrequest:succesS
@H_772_214@JSON: {
    args =     {
    };
    data = "";
    files =     {
    };
    form =     {
        "baz[]" =         (
            a,1
        );
        foo = bar;
        "qux[x]" = 1;
        "qux[y]" = 2;
        "qux[z]" = 3;
    };
    headers =     {
        Accept = "*/*";
        "Accept-Encoding" = "gzip;q=1.0,compress;q=0.5";
        "Accept-Language" = "en-US;q=1.0";
        "Content-Length" = 70;
        "Content-Type" = "application/x-www-form-urlencoded; charset=utf-8";
        Host = "httpbin.org";
        "User-Agent" = "Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))";
    };
    json = "<null>";
    origin = "202.115.52.205";
    url = "https://httpbin.org/post";
}

上传文件

示例代码

func upload()  {
        // 可任意拖一张图片到工程目录下重命名为“123.png”
        let fileURL = NSBundle.mainBundle().URLForresource("123",withExtension: "png")!
        Alamofire.upload(.POST,file: fileURL)
                 .progress { (bytesWritten,@R_251_1@R_616_11226@6@lBytesWritten,@R_251_1@R_616_11226@6@lBytesExpectedToWritE) in
                    //如果要修改界面UI,需要放到主线程中进行
                    dispatch_async(dispatch_get_main_queue()) {
                        print("@R_251_1@R_616_11226@6@l bytes written on main queue: \(@R_251_1@R_616_11226@6@lBytesWritten)")
                    }
        }
                 .responseString { (responsE) in
                    debugPrint("uploadrequest:\(responsE)")  
        }

    }

运行结果

@R_251_1@R_616_11226@6@l bytes written on @H_5_347@main queue: 3538
"uploadrequest:succesS: {\n  \"args\": {},\n  \"data\": \"data:application/octet-stream;base64,(此处省略文件data信息)==\",\n  \"files\": {},\n  \"form\": {},\n  \"headers\": {\n    \"Accept\": \"*/*\",\n    \"Accept-Encoding\": \"gzip;q=1.0,compress;q=0.5\",\n    \"Accept-Language\": \"en-US;q=1.0\",\n    \"Content-Length\": \"3538\",\n    \"Content-Type\": \"application/octet-stream\",\n    \"Host\": \"httpbin.org\",\n    \"User-Agent\": \"Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))\"\n  },\n  \"json\": null,\n  \"origin\": \"202.115.52.205\",\n  \"url\": \"https://httpbin.org/post\"\n}\n"

下载文件

示例代码

func download()  { 
        //设置下载目标路径为推荐下载目标路径
        let desTination = Alamofire.request.suggestedDownloadDesTination(directory: .DocumentDirectory,domain: .UserDomainMask)
        //打印下载目标路径
        print(NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,truE)[0])
        Alamofire.download(.GET,"https://httpbin.org/stream/100",desTination: desTination)
                 .response { (_,_,error) in
                    if let error = error {
                        print("Failed with error: \(error)")
                    } else {
                        print("Downloaded file successfully")
                    }
        }

    }

运行结果

/Users/nothinglhw/Library/Developer/CoreSimulator/Devices/560AA615-771E-499E-A8A9-AA6BE3781903/data/Containers/Data/Application/C715D9C3-57C9-40AF-88EC-EE4B86EB06D2/Documents
Downloaded file successfully

如果是在模拟器中运行,打开该目录可以看到多了一个名字为“100”的文件

打开该文件可以看到:

{"url": "https://httpbin.org/stream/100","headers": {"Host": "httpbin.org","Accept-Language": "en-US;q=1.0","Accept-Encoding": "gzip;q=1.0,compress;q=0.5","Accept": "*/*","User-Agent": "Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))"},"args": {},"id": 0,"origin": "202.115.52.205"}
{"url": "https://httpbin.org/stream/100","id": 1,"id": 2,"id": 3,"id": 4,"id": 5,"id": 6,"origin": "202.115.52.205"}

深入学习

这里只列出了最常用的几种操作,如果你希望能够更加深入地学习Alamofire,可以前往GitHub-Alamofire主页

大佬总结

以上是大佬教程为你收集整理的[快速学会Swift第三方库] Alamofire篇全部内容,希望文章能够帮你解决[快速学会Swift第三方库] Alamofire篇所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。