系统自带的 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.
相关推荐
7. **网络编程**:开源应用可能包含了使用URLSession或其他第三方库进行网络请求的代码,这涉及到JSON解析、HTTP状态码处理和错误恢复策略等网络编程技巧。 8. **数据持久化**:Swift-Radio-Pro可能使用Core Data或...
Swift请求(swift-request)是一个专为SwiftUI设计的声明式HTTP网络库,它提供了一种简单、直观的方式来处理网络请求,使开发者能够更专注于构建优雅的用户界面,而不是底层网络通信的复杂性。这个库的核心理念是将...
6. **性能优化**:鉴于Swift语言本身的高性能特点,Swift-web 可能利用非阻塞I/O和异步编程来提升服务器处理并发请求的能力,提高整体性能。 7. **依赖注入**:为了增强代码的灵活性和可测试性,Swift-web 可能支持...
manager.POST("https://api.example.com/upload", parameters: params, constructingBodyWith: { (request, data, error) -> Void in request.HTTPBody = imageData }, progress: nil, success: { (task, response)...
) -> Void, failure:@escaping (Error) -> Void) { let manager = AFHTTPRequestOperationManager() manager.requestSerializer = AFHTTPRequestSerializer() manager.responseSerializer = ...
func gzipData(_ data: Data) -> Data? { var compressedData = NSMutableData(capacity: Int(data.count * 1.1)) let zlibStream = zlib.DeflateStream() zlibStream.init(deflate: zlib.DEFLATE, level: zlib....
static func getUserData(completion: @escaping (Result, Error>) -> Void) { let url = "https://api.example.com/users" Alamofire.request(url).responseJSON { response in switch response.result { case...
Swift-Tool JHURLAnalyseTool 是一个专为Swift开发者设计的实用工具,主要用于截取和分析应用程序中的网络请求URL。这款工具可以帮助开发者快速、直观地了解应用在运行时发送的所有HTTP请求,对于调试和优化网络性能...
总的来说,`swift-AFNetworkActivityLogger`是一个强大的工具,它使得在Swift应用中管理和调试网络请求变得更为便捷。通过使用这个扩展,开发者可以更有效地诊断网络问题,优化性能,并确保应用程序的网络层按照预期...
1. **网络请求库的使用**:Alamofire是一个流行的Swift网络库,它简化了HTTP请求的处理。开发者可以使用`Alamofire.request()`方法发起GET或POST请求,然后使用响应序列化处理返回的数据。在获取地址数据时,我们...
.map { JSON -> MyDataModel in // 解析 JSON 数据到 MyDataModel } .catch { error in // 处理错误 } .subscribe(onNext: { data in // 使用解析后的数据 }, onError: { error in // 处理网络错误 }) ....
在Swift开发中,网络请求是应用与服务器交互的基础,而`NSURLSession`是Apple提供的一个强大的网络编程接口。本文将深入探讨如何对`NSURLSession`进行封装,以实现带有缓存功能的网络请求,包括查看缓存大小和清除...
在压缩包`swift-server-http-f8516cc`中,很可能包含了该项目的一个特定版本的源代码。通过查看源代码,开发者可以学习如何组织HTTP API的实现,理解其内部工作原理,以及如何将其与其他Swift服务器端技术(如数据库...
Swift-Bridge是一个专门为iOS开发设计的HTTP网络库,它的特点是高度可扩展,允许开发者在HTTP请求的生命周期中插入自定义的处理步骤。这个库利用了Swift语言的强大功能,特别是其元编程特性,使得网络请求的处理更加...
@objc func doSomethingInNative() -> Void { // 在这里实现Swift代码 } } ``` **三、配置RN桥接** 1. 在`MyRNProject/ios/MyRNProject/Info.plist`文件中,添加`NSAppTransportSecurity`节点以允许HTTP请求...
Swift的URLSession是处理网络请求的标准库,它可以用来发送HTTP请求并接收响应。同时,JSONSerialization类可以帮助我们将服务器返回的JSON数据解析为Swift对象。 在开发过程中,版本控制工具如Git也扮演着重要角色...
Swift-Lark是一个基于Swift编程语言实现的SOAP(Simple Object Access Protocol)库,它为开发者提供了在Swift环境中方便地处理SOAP请求和响应的能力。SOAP是一种基于XML的协议,用于在Web服务中交换结构化和类型化...
Swift-Guardian是一个针对Swift服务端框架Vapor3设计的Middleware,它的主要功能是实现访问控制,通过监控和管理客户端的IP地址以及他们对特定URL的请求频率,从而有效地防止DDoS攻击或过度请求。这个Middleware允许...
4. **网络编程**:可能使用URLSession进行HTTP请求,获取和发送数据,实现登录、好友请求、消息推送等功能。 5. **JSON解析**:由于网络数据通常以JSON格式传输,项目中可能会使用JSONSerialization进行解析和序列化...