{"id":1622,"url":"https://github.com/daltoniam/SwiftHTTP","last_synced_at":"2025-08-13T16:33:10.922Z","repository":{"id":17946037,"uuid":"20927524","full_name":"daltoniam/SwiftHTTP","owner":"daltoniam","description":"Thin wrapper around NSURLSession in swift. Simplifies HTTP requests.","archived":false,"fork":false,"pushed_at":"2021-05-17T18:23:45.000Z","size":253,"stargazers_count":1880,"open_issues_count":23,"forks_count":322,"subscribers_count":104,"default_branch":"master","last_synced_at":"2024-04-04T11:01:30.861Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/daltoniam.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-06-17T14:50:53.000Z","updated_at":"2024-04-04T03:40:57.000Z","dependencies_parsed_at":"2022-08-07T09:00:25.077Z","dependency_job_id":null,"html_url":"https://github.com/daltoniam/SwiftHTTP","commit_stats":null,"previous_names":[],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/daltoniam%2FSwiftHTTP","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/daltoniam%2FSwiftHTTP/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/daltoniam%2FSwiftHTTP/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/daltoniam%2FSwiftHTTP/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/daltoniam","download_url":"https://codeload.github.com/daltoniam/SwiftHTTP/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":213947801,"owners_count":15661352,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-01-05T20:15:51.618Z","updated_at":"2024-08-22T16:31:08.392Z","avatar_url":"https://github.com/daltoniam.png","language":"Swift","funding_links":[],"categories":["Networking","Libs","HarmonyOS","HTTP","Network","IOS 或 OSX","Network [🔝](#readme)","OOM-Leaks-Crash","Programming Languages"],"sub_categories":["Video","Network","Other free courses","Windows Manager","Networks","Swift"],"readme":"SwiftHTTP\n=========\n\nSwiftHTTP is a thin wrapper around NSURLSession in Swift to simplify HTTP requests.\n\n## Features\n\n- Convenient Closure APIs\n- Simple Queue Support\n- Parameter Encoding\n- Builtin JSON Request Serialization\n- Upload/Download with Progress Closure\n- Concise Codebase.\n\n\nFirst thing is to import the framework. See the Installation instructions on how to add the framework to your project.\n\n```swift\nimport SwiftHTTP\n```\n\n## Examples\n\n### GET\n\nThe most basic request. By default an Data object will be returned for the response.\n```swift\nHTTP.GET(\"https://google.com\") { response in\n\tif let err = response.error {\n\t\tprint(\"error: \\(err.localizedDescription)\")\n\t\treturn //also notify app of failure as needed\n\t}\n    print(\"opt finished: \\(response.description)\")\n    //print(\"data is: \\(response.data)\") access the response of the data with response.data\n}\n```\n\nWe can also add parameters as with standard container objects and they will be properly serialized to their respective HTTP equivalent.\n\n```swift\n//the url sent will be https://google.com?hello=world\u0026param2=value2\nHTTP.GET(\"https://google.com\", parameters: [\"hello\": \"world\", \"param2\": \"value2\"]) { response in\n\tif let err = response.error {\n\t\tprint(\"error: \\(err.localizedDescription)\")\n\t\treturn //also notify app of failure as needed\n\t}\n    print(\"opt finished: \\(response.description)\")\n}\n```\n\nThe `Response` contains all the common HTTP response data, such as the responseObject of the data and the headers of the response.\n\n### HTTP Methods\n\nAll the common HTTP methods are avalaible as convenience methods as well.\n\n### POST\n\n```swift\nlet params = [\"param\": \"param1\", \"array\": [\"first array element\",\"second\",\"third\"], \"num\": 23, \"dict\": [\"someKey\": \"someVal\"]]\nHTTP.POST(\"https://domain.com/new\", parameters: params) { response in\n//do things...\n}\n```\n\n### PUT\n\n```swift\nHTTP.PUT(\"https://domain.com/1\")\n```\n\n### HEAD\n\n```swift\nHTTP.HEAD(\"https://domain.com/1\")\n```\n\n### DELETE\n\n```swift\nHTTP.DELETE(\"https://domain.com/1\")\n```\n\n### Download\n\n```swift\nHTTP.Download(\"http://www.cbu.edu.zm/downloads/pdf-sample.pdf\", completion: { (response, url) in\n    //move the temp file to desired location...\n})\n```\n\n### Upload\n\nFile uploads can be done using the `Upload` object. All files to upload should be wrapped in a Upload object and added as a parameter.\n\n```swift\nlet fileUrl = URL(fileURLWithPath: \"/Users/dalton/Desktop/testfile\")!\nHTTP.POST(\"https://domain.com/new\", parameters: [\"aParam\": \"aValue\", \"file\": Upload(fileUrl: fileUrl)]) { response in\n//do things...\n}\n```\n`Upload` comes in both a on disk fileUrl version and a Data version.\n\n### Custom Headers\n\nCustom HTTP headers can be add to a request with the standard NSMutableRequest API:\n\n```swift\nHTTP.GET(\"https://domain.com\", parameters: [\"hello\": \"there\"], headers: [\"header\": \"value\"]) { response in\n    //do stuff\n}\n```\n\n### SSL Pinning\n\nSSL Pinning is also supported in SwiftHTTP. \n\n```swift\nvar req = URLRequest(urlString: \"https://domain.com\")!\nreq?.timeoutInterval = 5\nlet task = HTTP(req)\ntask.security = HTTPSecurity(certs: [HTTPSSLCert(data: data)], usePublicKeys: true)\n//opt.security = HTTPSecurity() //uses the .cer files in your app's bundle\ntask.run { (response) in\n    if let err = response.error {\n        print(\"error: \\(err.localizedDescription)\")\n        return //also notify app of failure as needed\n    }\n    print(\"opt finished: \\(response.description)\")\n}\n```\nYou load either a `Data` 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.\n\n### Authentication\n\nSwiftHTTP supports authentication through [NSURLCredential](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCredential_Class/Reference/Reference.html). Currently only Basic Auth and Digest Auth have been tested.\n\n```swift\nvar req = URLRequest(urlString: \"https://domain.com\")!\nreq.timeoutInterval = 5\nlet task = HTTP(req)\n//the auth closures will continually be called until a successful auth or rejection\nvar attempted = false\ntask.auth = { challenge in\n    if !attempted {\n        attempted = true\n        return NSURLCredential(user: \"user\", password: \"passwd\", persistence: .ForSession)\n    }\n    return nil //auth failed, nil causes the request to be properly cancelled.\n}\ntask.run { (response) in\n   //do stuff\n}\n```\n\nAllow all certificates example:\n\n```swift\nvar req = URLRequest(urlString: \"https://domain.com\")!\nreq.timeoutInterval = 5\nlet task = HTTP(req)\n//the auth closures will continually be called until a successful auth or rejection\nvar attempted = false\ntask.auth = { challenge in\n    if !attempted {\n        attempted = true\n        return NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)\n    }\n    return nil //auth failed, nil causes the request to be properly cancelled.\n}\ntask.run { (response) in\n   //do stuff\n}\n```\n\n### Operation Queue\n\nSwiftHTTP also has a simple queue in it!\n\n```swift\nlet queue = HTTPQueue(maxSimultaneousRequest: 2)\nvar req = URLRequest(urlString: \"https://google.com\")!\nreq.timeoutInterval = 5\nlet task = HTTP(req)\ntask.onFinish = { (response) in\n    print(\"item in the queue finished: \\(response.URL!)\")\n}\nqueue.add(http: task) //the request will start running once added to the queue\n\n\nvar req2 = URLRequest(urlString: \"https://apple.com\")!\nreq2.timeoutInterval = 5\nlet task2 = HTTP(req2)\ntask2.onFinish = { (response) in\n    print(\"item in the queue finished: \\(response.URL!)\")\n}\nqueue.add(http: task2)\n\n//etc...\n\nqueue.finished {\n    print(\"all items finished\")\n}\n```\n\n### Cancel\n\nLet's say you want to cancel the request a little later, call the `cancel` method.\n\n```swift\ntask.cancel()\n```\n\n### JSON Request Serializer\n\nRequest parameters can also be serialized to JSON as needed. By default request are serialized using standard HTTP form encoding.\n\n```swift\nHTTP.GET(\"https://google.com\", requestSerializer: JSONParameterSerializer()) { response in\n    //you already get it. The data property of the response object will have the json in it\n}\n```\n\n### Progress\n\nSwiftHTTP can monitor the progress of a request.\n\n```swift\nvar req = URLRequest(urlString: \"https://domain.com/somefile\")\nlet task = HTTP(req!)\ntask.progress = { progress in\n    print(\"progress: \\(progress)\") //this will be between 0 and 1.\n}\ntask.run { (response) in\n   //do stuff\n}\n```\n\n\n### Global handlers\n\nSwiftHTTP also has global handlers, to reduce the requirement of repeat HTTP modifiers, such as a auth header or setting `NSMutableURLRequest` properties such as `timeoutInterval`. \n\n```swift\n//modify NSMutableURLRequest for any Factory method call (e.g. HTTP.GET, HTTP.POST, HTTP.New, etc).\nHTTP.globalRequest { req in\n    req.timeoutInterval = 5\n}\n\n//set a global SSL pinning setting\nHTTP.globalSecurity(HTTPSecurity()) //see the SSL section for more info\n\n//set global auth handler. See the Auth section for more info\nHTTP.globalAuth { challenge in\n    return NSURLCredential(user: \"user\", password: \"passwd\", persistence: .ForSession)\n}\n```\n\n## Client/Server Example\n\nThis is a full example swiftHTTP in action. First here is a quick web server in Go.\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/bar\", func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"got a web request\")\n\t\tfmt.Println(\"header: \", r.Header.Get(\"someKey\"))\n\t\tw.Write([]byte(\"{\\\"status\\\": \\\"ok\\\"}\"))\n\t})\n\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\nNow for the request:\n\n```swift\nstruct Response: Codable {\n    let status: String\n}\n\nlet decoder = JSONDecoder()\nHTTP.GET(\"http://localhost:8080/bar\") { response in\n    if let error = response.error {\n        print(\"got an error: \\(error)\")\n        return\n    }\n    do {\n        let resp = try decoder.decode(Response.self, from: response.data)\n        print(\"completed: \\(resp.status)\")\n    } catch let error {\n        print(\"decode json error: \\(error)\")\n    }\n}\n```\n\n## POST example\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \"net/http\"\n    \"os\"\n)\n\nfunc main() {\n    http.HandleFunc(\"/bar\", func(w http.ResponseWriter, r *http.Request) {\n        fmt.Println(\"header: \", r.Header.Get(\"Content-Type\"))\n        upload, header, err := r.FormFile(\"file\")\n        if err != nil {\n            w.Write([]byte(\"{\\\"error\\\": \\\"bad file upload\\\"}\")) //normally be a 500 status code\n            return\n        }\n        file, err := os.Create(header.Filename) // we would normally need to generate unique filenames.\n        if err != nil {\n            w.Write([]byte(\"{\\\"error\\\": \\\"system error occured\\\"}\")) //normally be a 500 status code\n            return\n        }\n        io.Copy(file, upload) // write the uploaded file to disk.\n        w.Write([]byte(\"{\\\"status\\\": \\\"ok\\\"}\")) \n    })\n\n    log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\nNow for the Swift:\n\n```swift\nstruct Response: Codable {\n    let status: String?\n    let error: String?\n}\n\nlet decoder = JSONDecoder()\nlet url = URL(fileURLWithPath: \"/Users/dalton/Desktop/picture.jpg\")\nHTTP.POST(\"http://localhost:8080/bar\", parameters: [\"test\": \"value\", \"file\": Upload(fileUrl: url)]) { response in\n    if let error = response.error {\n        print(\"got an error: \\(error)\")\n        return\n    }\n    do {\n        let resp = try decoder.decode(Response.self, from: response.data)\n        if let err = resp.error {\n            print(\"got an error: \\(err)\")\n        }\n        if let status = resp.status {\n            print(\"completed: \\(status)\")\n        }\n    } catch let error {\n        print(\"decode json error: \\(error)\")\n    }\n}\n```\n\n## Requirements\n\nSwiftHTTP works with iOS 7/OSX 10.10 or above. It is recommended to use iOS 8/10.10 or above for CocoaPods/framework support.\nTo use SwiftHTTP with a project targeting iOS 7, you must include all Swift files directly in your project.\n\n## Installation\n\n### CocoaPods\n\nCheck out [Get Started](https://guides.cocoapods.org/using/getting-started.html) tab on [cocoapods.org](http://cocoapods.org/).\n\nTo use SwiftHTTP in your project add the following 'Podfile' to your project\n\n\tsource 'https://github.com/CocoaPods/Specs.git'\n\tplatform :ios, '8.0'\n\tuse_frameworks!\n\n\tpod 'SwiftHTTP', '~\u003e 3.0.1'\n\nThen run:\n\n    pod install\n\n### Carthage\n\nCheck out the [Carthage](https://github.com/Carthage/Carthage) docs on how to add a install. The `SwiftHTTP` framework is already setup with shared schemes.\n\n[Carthage Install](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application)\n\nYou can install Carthage with [Homebrew](http://brew.sh/) using the following command:\n\n```bash\n$ brew update\n$ brew install carthage\n```\n\nTo integrate SwiftHTTP into your Xcode project using Carthage, specify it in your `Cartfile`:\n\n```\ngithub \"daltoniam/SwiftHTTP\" \u003e= 3.0.1\n```\n\n### Rogue\n\nFirst see the [installation docs](https://github.com/acmacalister/Rogue) for how to install Rogue.\n\nTo install SwiftHTTP run the command below in the directory you created the rogue file.\n\n```\nrogue add https://github.com/daltoniam/SwiftHTTP\n```\n\nNext 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.\n\n### Other\n\nSimply grab the framework (either via git submodule or another package manager).\n\nAdd 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.\n\n### Add Copy Frameworks Phase\n\nIf 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`.\n\n## TODOs\n\n- [ ] Linux support?\n- [ ] Add more unit tests\n\n## License\n\nSwiftHTTP is licensed under the Apache v2 License.\n\n## Contact\n\n### Dalton Cherry\n* https://github.com/daltoniam\n* http://twitter.com/daltoniam\n* http://daltoniam.com\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdaltoniam%2FSwiftHTTP","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdaltoniam%2FSwiftHTTP","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdaltoniam%2FSwiftHTTP/lists"}