Swift网络请求库Alamofire

Alamofire由cnoon大神编写的基于swift的网络请求库
Github下载地址
[TOC]

运行限制:

  • iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 7.3+

CocoaPods安装:

1.下载CocoaPods

$ gem install cocoapods

CocoaPods 0.39.0+ is required to build Alamofire 3.0.0+.
2.修改Podfile文件:

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

pod 'Alamofire', '~> 3.3'

3.下载:

$ pod install

使用Alamofire

发出请求

import Alamofire
Alamofire.request(.GET, url)

响应处理

Alamofire.request(.GET, url, parameters: ["key": "value"])
         .responseJSON { response in
             print(response.request)  
             print(response.response) 
             print(response.data)   
             print(response.result) 
             if let JSON = response.result.value {
                 print("JSON: \(JSON)")
             }
         }

响应JSON处理

Alamofire.request(.GET, url)
         .responseJSON { response in
             debugPrint(response)
         }

HTTP方法

public enum Method: String {
    case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
}

上传文件

let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png")
Alamofire.upload(.POST, url, file: fileURL)

上传进度

Alamofire.upload(.POST, url, file: fileURL)
         .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
             print(totalBytesWritten)

             // This closure is NOT called on the main queue for performance
             // reasons. To update your ui, dispatch to the main queue.
             dispatch_async(dispatch_get_main_queue()) {
                 print("Total bytes written on main queue: \(totalBytesWritten)")
             }
         }
         .responseJSON { response in
             debugPrint(response)
         }

下载

Alamofire.download(.GET, url) { temporaryURL, response in
    let fileManager = NSFileManager.defaultManager()
    let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    let pathComponent = response.suggestedFilename

    return directoryURL.URLByAppendingPathComponent(pathComponent!)
}

HTTP头部

Alamofire.request(.GET, url, headers: ["key":"value"])
         .responseJSON { response in
             debugPrint(response)
         }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值