系统自带的 URLSession 实现 HTTP 请求
let url = URL(string:"http://xxx.com"); URLSession(configuration: .default).dataTask(with: url!, completionHandler: { (data, rsp, error) in //do some thing }).resume()
使用第三方库 SwiftHTTP
https://github.com/daltoniam/SwiftHTTP
库包 也可 看附件
使用方法
Examples
GET
The most basic request. By default an NSData object will be returned for the response.
do {
let opt =try HTTP.GET("https://google.com")
opt.start { response iniflet err = response.error {
print("error: \(err.localizedDescription)")
return//also notify app of failure as needed
}
print("opt finished: \(response.description)")
//print("opt finished: \(response.text! as String)")
//异步返回处理主线程UI
dispatch_async(dispatch_get_main_queue(), {
self.hideToast();
});
}
} catchlet error {
print("got an error creating the request: \(error)")
}
We can also add parameters as with standard container objects and they will be properly serialized to their respective HTTP equivalent.
do {
//the url sent will be https://google.com?hello=world¶m2=value2
let opt = try HTTP.GET("https://google.com", parameters: ["hello": "world", "param2": "value2"])
opt.start { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
return //also notify app of failure as needed
}
print("opt finished: \(response.description)")
}
} catch let error {
print("got an error creating the request: \(error)")
}
The HTTPResponse
contains all the common HTTP response data, such as the responseObject of the data and the headers of the response.
HTTP Methods
All the common HTTP methods are avalaible as convenience methods as well.
POST
let params = ["param": "param1", "array": ["first array element","second","third"], "num": 23, "dict": ["someKey": "someVal"]]
do {
let opt = try HTTP.POST("https://domain.com/new", parameters: params)
opt.start { response in
//do things...
}
} catch let error {
print("got an error creating the request: \(error)")
}
PUT
let opt = try HTTP.PUT("https://domain.com/1")
HEAD
let opt = try HTTP.HEAD("https://domain.com/1")
DELETE
let opt = try HTTP.DELETE("https://domain.com/1")
Background Downloads
//TODO implement background download...
Upload
File uploads can be done using the Upload
object. All files to upload should be wrapped in a Upload object and added as a parameter.
let fileUrl = NSURL(fileURLWithPath: "/Users/dalton/Desktop/testfile")!
do {
let opt = try HTTP.POST("https://domain.com/new", parameters: ["aParam": "aValue", "file": Upload(fileUrl: fileUrl)])
opt.start { response in
//do things...
}
} catch let error {
print("got an error creating the request: \(error)")
}
Upload
comes in both a on disk fileUrl version and a NSData version.
Custom Headers
Custom HTTP headers can be add to a request with the standard NSMutableRequest API:
do {
let opt = try HTTP.GET("https://domain.com", parameters: ["hello": "there"], headers: ["header": "value"])
opt.start { response in
//do stuff
}
} catch let error {
print("couldn't serialize the paraemeters: \(error)")
}
SSL Pinning
SSL Pinning is also supported in SwiftHTTP.
do {
let opt = try HTTP.GET("https://domain.com")
opt.security = HTTPSecurity(certs: [HTTPSSLCert(data: data)], usePublicKeys: true)
//opt.security = HTTPSecurity() //uses the .cer files in your app's bundle
opt.start { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
return //also notify app of failure as needed
}
print("opt finished: \(response.description)")
}
} catch let error {
print("got an error creating the request: \(error)")
}
You load either a NSData
blob of your certificate or you can use a SecKeyRef
if you have a public key you want to use. The usePublicKeys
bool is whether to use the certificates for validation or the public keys. The public keys will be extracted from the certificates automatically if usePublicKeys
is choosen.
Authentication
SwiftHTTP supports authentication through NSURLCredential. Currently only Basic Auth and Digest Auth have been tested.
do {
let opt = try HTTP.GET("https://domain.com")
//the auth closures will continually be called until a successful auth or rejection
var attempted = false
opt.auth = { challenge in
if !attempted {
attempted = true
return NSURLCredential(user: "user", password: "passwd", persistence: .ForSession)
}
return nil //auth failed, nil causes the request to be properly cancelled.
}
opt.start { response in
//do stuff
}
} catch let error {
print("got an error creating the request: \(error)")
}
Allow all certificates example:
do {
let opt = try HTTP.GET("https://domain.com")
//the auth closures will continually be called until a successful auth or rejection
var attempted = false
opt.auth = { challenge in
if !attempted {
attempted = true
return NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
}
return nil
}
opt.start { response in
//do stuff
}
} catch let error {
print("got an error creating the request: \(error)")
}
Operation Queue
Operation queues are also supported in SwiftHTTP.
let operationQueue = NSOperationQueue()
operationQueue.maxConcurrentOperationCount = 2
do {
let opt = try HTTP.New("https://google.com", method: .GET)
opt.onFinish = { response in
//do stuff
}
operationQueue.addOperation(opt)
} catch let error {
print("got an error creating the request: \(error)")
}
Cancel
Let's say you want to cancel the request a little later, call the cancel
method that we get from it being an NSOperation subclass.
opt.cancel()
JSON Request Serializer
Request parameters can also be serialized to JSON as needed. By default request are serialized using standard HTTP form encoding.
do {
let opt = try HTTP.New("https://google.com", method: .GET, requestSerializer: JSONParameterSerializer())
opt.onFinish = { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
return //also notify app of failure as needed
}
print("opt finished: \(response.description)")
}
} catch let error {
print("got an error creating the request: \(error)")
}
Progress
SwiftHTTP can monitor the progress of a request.
do {
let opt = try HTTP.GET("https://domain.com/somefile")
opt.progress = { progress in
print("progress: \(progress)") //this will be between 0 and 1.
}
opt.start { response in
//do stuff
}
} catch let error {
print("got an error creating the request: \(error)")
}
Global handlers
SwiftHTTP also has global handlers, to reduce the requirement of repeat HTTP modifiers, such as a auth header or setting NSMutableURLRequest
properties such as timeoutInterval
.
//modify NSMutableURLRequest for any Factory method call (e.g. HTTP.GET, HTTP.POST, HTTP.New, etc).
HTTP.globalRequest { req in
req.timeoutInterval = 5
}
//set a global SSL pinning setting
HTTP.globalSecurity(HTTPSecurity()) //see the SSL section for more info
//set global auth handler. See the Auth section for more info
HTTP.globalAuth { challenge in
return NSURLCredential(user: "user", password: "passwd", persistence: .ForSession)
}
Client/Server Example
This is a full example swiftHTTP in action. First here is a quick web server in Go.
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
log.Println("got a web request")
fmt.Println("header: ", r.Header.Get("someKey"))
w.Write([]byte("{\"status\": \"ok\"}"))
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
Now for the request:
struct Response: JSONJoy {
let status: String?
init(_ decoder: JSONDecoder) {
status = decoder["status"].string
}
}
do {
let opt = try HTTP.GET("http://localhost:8080/bar")
opt.start { response in
if let error = response.error {
print("got an error: \(error)")
return
}
let resp = Response(JSONDecoder(response.data))
if let status = resp.status {
print("completed: \(status)")
}
}
} catch let error {
print("got an error: \(error)")
}
POST example
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
fmt.Println("header: ", r.Header.Get("Content-Type"))
upload, header, err := r.FormFile("file")
if err != nil {
w.Write([]byte("{\"error\": \"bad file upload\"}")) //normally be a 500 status code
return
}
file, err := os.Create(header.Filename) // we would normally need to generate unique filenames.
if err != nil {
w.Write([]byte("{\"error\": \"system error occured\"}")) //normally be a 500 status code
return
}
io.Copy(file, upload) // write the uploaded file to disk.
w.Write([]byte("{\"status\": \"ok\"}"))
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
Now for the Swift:
struct Response: JSONJoy {
let status: String?
let error: String?
init(_ decoder: JSONDecoder) {
status = decoder["status"].string
error = decoder["error"].string
}
}
do {
let url = NSURL(fileURLWithPath: "/Users/dalton/Desktop/dalton.jpeg")
let opt = try HTTP.POST("http://localhost:8080/bar", parameters: ["test": "value", "file": Upload(fileUrl: url)])
opt.start { response in
if let error = response.error {
print("got an error: \(error)")
return
}
let resp = Response(JSONDecoder(response.data))
if let err = resp.error {
print("got an error: \(err)")
}
if let status = resp.status {
print("completed: \(status)")
}
}
} catch let error {
print("got an error: \(error)")
}
JSON Parsing
Swift has a lot of great JSON parsing libraries, but I made one specifically designed for JSON to object serialization.
Requirements
SwiftHTTP works with iOS 7/OSX 10.10 or above. It is recommended to use iOS 8/10.10 or above for CocoaPods/framework support. To use SwiftHTTP with a project targeting iOS 7, you must include all Swift files directly in your project.
Installation
CocoaPods
Check out Get Started tab on cocoapods.org.
To use SwiftHTTP in your project add the following 'Podfile' to your project
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'SwiftHTTP', '~> 1.0.4'
Then run:
pod install
Carthage
Check out the Carthage docs on how to add a install. The SwiftHTTP
framework is already setup with shared schemes.
You can install Carthage with Homebrew using the following command:
$ brew update
$ brew install carthage
To integrate SwiftHTTP into your Xcode project using Carthage, specify it in your Cartfile
:
github "daltoniam/SwiftHTTP" >= 1.0.4
Rogue
First see the installation docs for how to install Rogue.
To install SwiftHTTP run the command below in the directory you created the rogue file.
rogue add https://github.com/daltoniam/SwiftHTTP
Next open the libs
folder and add the SwiftHTTP.xcodeproj
to your Xcode project. Once that is complete, in your "Build Phases" add the SwiftHTTP.framework
to your "Link Binary with Libraries" phase. Make sure to add the libs
folder to your .gitignore
file.
Other
Simply grab the framework (either via git submodule or another package manager).
Add the SwiftHTTP.xcodeproj
to your Xcode project. Once that is complete, in your "Build Phases" add the SwiftHTTP.framework
to your "Link Binary with Libraries" phase.
Add Copy Frameworks Phase
If you are running this in an OSX app or on a physical iOS device you will need to make sure you add the SwiftHTTP.framework
included in your app bundle. To do this, in Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar. In the tab bar at the top of that window, open the "Build Phases" panel. Expand the "Link Binary with Libraries" group, and add SwiftHTTP.framework
. Click on the + button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add SwiftHTTP.framework
.
TODOs
- Linux support?
- Add more unit tests
License
SwiftHTTP is licensed under the Apache v2 License.
相关推荐
swift-request:声明式HTTP网络,专为SwiftUI设计
一个优雅的库,用于在Swift中存根HTTP请求,允许您使用NSURLConnection或NSURLSession存根任何HTTP / HTTPS。 这包括来自Alamofire和AFNetworking等图书馆的任何请求。
数据请求 GZip数据压缩和解压缩问题
SwiftNIO HTTP / 2该项目包含对使用SwiftNIO的Swift项目的HTTP / 2支持。 请注意,该项目目前处于测试状态,并且可能会发生变化。 SwiftNIO HTTP / 2目前有许多限制。此项目包含对使用SwiftNIO的Swift项目的HTTP / 2...
SwiftHTTP 简单封装了 Swift 语言中的 NSURLSession ,简化了 HTTP 请求操作。 示例代码: var request = HTTPTask() request.GET("http://www.oschina.net/", parameters: nil, success: {(response: ...
Swift 写的tableview 的学习;tableview 的数据来源--http://apistore.baidu.com/apiworks/servicedetail/987.html 数据请求用Alamofire框架和AFNetworking 同一个作者
轻量级http请求,基于封装AFN3.x YYCache, 接口设计上,通过block返回创建好的请求模型对象,调用者只有对非默认值属性进行修改即可,接口调用完成也只通过一个block来回调,具体情况通过响应模型对象来解析
Swallow:简单好用的 web 通信工具-Swallow 封装了 HTTP 和 HTTPS 请求,设计良好的 API 用起来非常顺手。此外,Swallow 还支持链式操作和 JSON 解析,能满足绝大部分通信需求。
安装-入门-生成请求-可编码-如何工作-请求组-请求链-Json-贡献-许可证与SwiftUI一起使用安装swift-request可以通过Swi安装进行安装-入门-构建请求-可编码-工作原理-请求组-请求链-Json-贡献-使用SwiftUI安装使用许可...
基于AFNetworking的二次封装,建立http请求的单例对象,提供GET网络请求,POST网络请求,上传,下载,取消指定的网络请求,添加请求头等
KTVHTTPCache 是一个处理 HTTP 网络缓存的框架。设计之初是为了解决音视频在线播放的缓存问题。但其应用场景不仅限于音视频在线播放,也可以用于图片加载、文件下载、普通网络请求等场景。
AFNetworking是一个轻量级的iOS网络通信类库。它建立在NSURLConnection和NSOperation等类库的基础上,让很多网络通信功能的实现变...它支持HTTP请求和基于REST的网络服务(包括GET、POST、 PUT、DELETE等)。支持ARC。
swift 高仿 单糖 app,总体来说界面搭建还算简单,而且结构不是很复杂,本次项目完成了大部分界面,对于项目中的数据接口都是通过 Charles 抓包获得,基本每个界面都是有数据请求。 项目中有的地方代码写的不是很...
它包括显示基本Swift,JSON解析,发送HTTP请求以及执行基本文件IO的游乐场。用法克隆仓库。 git clone --recursive https://github.com/dmikusa/swift_playgrounds.git 在XCode中打开工作区。 等待它为所有内容建立...
快速检查员Swift 中间件将有关请求的信息中继回客户端。现任督察计时 - 向请求添加“Inspector-Timing”标头,指示代理服务器处理请求所花费的时间。 $ curl -i -H ' Inspector: Timing ' -XGET -H ' x-auth-token: ...
使用这个库,你可以在 HTTP 请求实际发送之前进行拦截,也可以在响应传递给用户之前进行拦截。熟悉 Swizzling 的同学已经想到了,利用这个特性可以给所有请求添加通用的处理操作,非常方便。
swift-request:为SwiftUI设计的声明性HTTP网络
将集成到您的Swift项目中的完美起点 ••••• ... 单击File -> Swift Packages -> Add Package Dependency ,输入InstantSearch存储库的URL 。 如果您是框架作者,并且使用Swift API Client作为依
九十九个Swift解决方案如果您喜欢编程挑战,我们会为您提供99个好的挑战。...第2步:克隆您的存储库要克隆您的分叉存储库,请输入: $ git clone https://www.github.com/<your>/Ninety-Nine-Swift-Solutions第3步