Thin wrapper around NSURLSession in swift. Simplifies HTTP requests.

Related tags

Networking SwiftHTTP
Overview

SwiftHTTP

SwiftHTTP is a thin wrapper around NSURLSession in Swift to simplify HTTP requests.

Features

  • Convenient Closure APIs
  • Simple Queue Support
  • Parameter Encoding
  • Builtin JSON Request Serialization
  • Upload/Download with Progress Closure
  • Concise Codebase.

First thing is to import the framework. See the Installation instructions on how to add the framework to your project.

import SwiftHTTP

Examples

GET

The most basic request. By default an Data object will be returned for the response.

HTTP.GET("https://google.com") { response in
	if let err = response.error {
		print("error: \(err.localizedDescription)")
		return //also notify app of failure as needed
	}
    print("opt finished: \(response.description)")
    //print("data is: \(response.data)") access the response of the data with response.data
}

We can also add parameters as with standard container objects and they will be properly serialized to their respective HTTP equivalent.

//the url sent will be https://google.com?hello=world&param2=value2
HTTP.GET("https://google.com", parameters: ["hello": "world", "param2": "value2"]) { response in
	if let err = response.error {
		print("error: \(err.localizedDescription)")
		return //also notify app of failure as needed
	}
    print("opt finished: \(response.description)")
}

The Response 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"]]
HTTP.POST("https://domain.com/new", parameters: params) { response in
//do things...
}

PUT

HTTP.PUT("https://domain.com/1")

HEAD

HTTP.HEAD("https://domain.com/1")

DELETE

HTTP.DELETE("https://domain.com/1")

Download

HTTP.Download("http://www.cbu.edu.zm/downloads/pdf-sample.pdf", completion: { (response, url) in
    //move the temp file to desired location...
})

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 = URL(fileURLWithPath: "/Users/dalton/Desktop/testfile")!
HTTP.POST("https://domain.com/new", parameters: ["aParam": "aValue", "file": Upload(fileUrl: fileUrl)]) { response in
//do things...
}

Upload comes in both a on disk fileUrl version and a Data version.

Custom Headers

Custom HTTP headers can be add to a request with the standard NSMutableRequest API:

HTTP.GET("https://domain.com", parameters: ["hello": "there"], headers: ["header": "value"]) { response in
    //do stuff
}

SSL Pinning

SSL Pinning is also supported in SwiftHTTP.

var req = URLRequest(urlString: "https://domain.com")!
req?.timeoutInterval = 5
let task = HTTP(req)
task.security = HTTPSecurity(certs: [HTTPSSLCert(data: data)], usePublicKeys: true)
//opt.security = HTTPSecurity() //uses the .cer files in your app's bundle
task.run { (response) in
    if let err = response.error {
        print("error: \(err.localizedDescription)")
        return //also notify app of failure as needed
    }
    print("opt finished: \(response.description)")
}

You 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.

Authentication

SwiftHTTP supports authentication through NSURLCredential. Currently only Basic Auth and Digest Auth have been tested.

var req = URLRequest(urlString: "https://domain.com")!
req.timeoutInterval = 5
let task = HTTP(req)
//the auth closures will continually be called until a successful auth or rejection
var attempted = false
task.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.
}
task.run { (response) in
   //do stuff
}

Allow all certificates example:

var req = URLRequest(urlString: "https://domain.com")!
req.timeoutInterval = 5
let task = HTTP(req)
//the auth closures will continually be called until a successful auth or rejection
var attempted = false
task.auth = { challenge in
    if !attempted {
        attempted = true
        return NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
    }
    return nil //auth failed, nil causes the request to be properly cancelled.
}
task.run { (response) in
   //do stuff
}

Operation Queue

SwiftHTTP also has a simple queue in it!

let queue = HTTPQueue(maxSimultaneousRequest: 2)
var req = URLRequest(urlString: "https://google.com")!
req.timeoutInterval = 5
let task = HTTP(req)
task.onFinish = { (response) in
    print("item in the queue finished: \(response.URL!)")
}
queue.add(http: task) //the request will start running once added to the queue


var req2 = URLRequest(urlString: "https://apple.com")!
req2.timeoutInterval = 5
let task2 = HTTP(req2)
task2.onFinish = { (response) in
    print("item in the queue finished: \(response.URL!)")
}
queue.add(http: task2)

//etc...

queue.finished {
    print("all items finished")
}

Cancel

Let's say you want to cancel the request a little later, call the cancel method.

task.cancel()

JSON Request Serializer

Request parameters can also be serialized to JSON as needed. By default request are serialized using standard HTTP form encoding.

HTTP.GET("https://google.com", requestSerializer: JSONParameterSerializer()) { response in
    //you already get it. The data property of the response object will have the json in it
}

Progress

SwiftHTTP can monitor the progress of a request.

var req = URLRequest(urlString: "https://domain.com/somefile")
let task = HTTP(req!)
task.progress = { progress in
    print("progress: \(progress)") //this will be between 0 and 1.
}
task.run { (response) in
   //do stuff
}

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: Codable {
    let status: String
}

let decoder = JSONDecoder()
HTTP.GET("http://localhost:8080/bar") { response in
    if let error = response.error {
        print("got an error: \(error)")
        return
    }
    do {
        let resp = try decoder.decode(Response.self, from: response.data)
        print("completed: \(resp.status)")
    } catch let error {
        print("decode json 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: Codable {
    let status: String?
    let error: String?
}

let decoder = JSONDecoder()
let url = URL(fileURLWithPath: "/Users/dalton/Desktop/picture.jpg")
HTTP.POST("http://localhost:8080/bar", parameters: ["test": "value", "file": Upload(fileUrl: url)]) { response in
    if let error = response.error {
        print("got an error: \(error)")
        return
    }
    do {
        let resp = try decoder.decode(Response.self, from: response.data)
        if let err = resp.error {
            print("got an error: \(err)")
        }
        if let status = resp.status {
            print("completed: \(status)")
        }
    } catch let error {
        print("decode json error: \(error)")
    }
}

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', '~> 3.0.1'

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.

Carthage Install

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" >= 3.0.1

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.

Contact

Dalton Cherry

Comments
  • Xcode 7 - Swift 2.0

    Xcode 7 - Swift 2.0

    I've forked this great library and I'm working on a basic swift 2.0 compatibility branch here https://github.com/mpclarkson/SwiftHTTP/tree/swift-2

    It's pretty rudimentary at the moment (e.g. no guards, throws etc) but once I have my project running in swift 2 and can test it properly I'll submit a pull request if you want?

    opened by mpclarkson 18
  • Importing framework

    Importing framework

    Hi there

    I'm new to Xcode and iOS so please bear with me. I don't seem to be able to import this into my iOS project.

    I have followed these steps in Xcode 6.1:

    1. Downloaded and unzipped the the 0.9.2 release
    2. Copied SwiftHTTP.xcodeproj into my project
    3. Under Build Phases > Link Binary with Libraries I have selected SwiftHTTP.framework
    4. Clicked the + and selected "New Copy Files Phase"
    5. Renamed this to "Copy Framework" and added SwiftHTTP.framework
    6. Set "Require Only App-Extension-Safe API" to Yes under Build Settings
    7. Added "#import SwiftHttp" in my controller
    8. Included a basic GET request task in the controller

    The framework files are red.

    When I compile I receive an "Apple Mach-O Linker Error":

    Undefined symbols for architecture x86_64:
      "__TFC9SwiftHttp8HTTPTaskCfMS0_FT_S0_", referenced from:
          __TFC12HileniumAuth14ViewController11viewDidLoadfS0_FT_T_ in ViewController.o
      "__TMaC9SwiftHttp8HTTPTask", referenced from:
          __TFC12HileniumAuth14ViewController11viewDidLoadfS0_FT_T_ in ViewController.o
    ld: symbol(s) not found for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    

    Any help would be much appreciated.

    Cheers Matt

    opened by mpclarkson 16
  • EXC_BAD_ACCESS in HTTPTask.swift

    EXC_BAD_ACCESS in HTTPTask.swift

    Hey, i have now ported everything to the new completionHandler and since then my HTTP requests fail. In the HTTPTask.swift on line 478:

    let blocks = self.backgroundTaskMap[session.configuration.identifier]
    

    Any ideas why this is happening? Greetings Leo

    opened by leo-unglaub 14
  • Integration with JSONJoy

    Integration with JSONJoy

    Hi, Im new in this, I'm wotking with Swift HTTP and JSONJoy Everything is OK and compile and upload to simulator, but when I call webservice I have an error on JSONJoy.framework, it says no image found Please can you help me

    opened by javierC1988 14
  • CFNetwork SSLHandshake failed (-9805)

    CFNetwork SSLHandshake failed (-9805)

    I'm trying to HTTP POST (using Swift) to my server and I'm getting this error:

    2015-01-04 20:09:43.196 PIPiOS[1308:47829] CFNetwork SSLHandshake failed (-9805) 2015-01-04 20:09:43.197 PIPiOS[1308:47829] NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9805)

    Any idea what's going on? POST works fine otherwise (using Java or PHP) Target: iOS8.1

    opened by theblixguy 11
  • repeating characters...

    repeating characters...

    Just pulled this down to test it out. Looks great.

    Pinged a local REST api and get the following

    {{""ssuucccceesss"s:"t:rtureu,e",i"di"d:"":8"78a78ab8466604-04-f41f71-71-11e14e-49-891881-8a-1a917937f3bfab8af8ef3e"3,"",a"caccocuonutnst"s:"[:][}]
    
    

    This is true with anything - errors, responses, etc. Repeats letters multiple times.

    opened by rblalock 11
  • Support for easy certificate pinning

    Support for easy certificate pinning

    Hey, certificate pinning has become more and more important. But sadly it's still very complicated to do in IOS. So i was hoping you would like to implement a simple abstraction around cert pinning in SwiftHTTP.

    What are your thoughts on the topic? Thanks and greetings Leo

    opened by leo-unglaub 10
  • Failed to install

    Failed to install

    I'm having this error after add your framework:

    SwiftHTTP-master/Tests/SwiftHTTPTests.swift:9:8: Cannot load underlying module for 'XCTest' SwiftHTTP-master/README.md' of type net.daringfireball.markdown for architecture i386

    opened by dzpt 9
  • EXC_BAD_ACCESS in Requests.swift (collect.appendContentsOf...)

    EXC_BAD_ACCESS in Requests.swift (collect.appendContentsOf...)

    Line 122 and 151 - collect.appendContentsOf(subParam.createPairs(useKey))

    This problem only happens when i use my release schema. (no zombie objects etc.). @pappzsolt100 had already posted an issue, but this workaround didn't work for me - issue: #155

    I've replaced the collect.appendContentsOf with an iteration through the array:

    ...
    for s in subParam.createPairs(useKey) {
     collect.append(s)
    }
    ...
    
    opened by floscom 8
  • Handling Timeout to Recall the Function

    Handling Timeout to Recall the Function

    Hi,

    Is there any way that I can handle the time out, like, if it takes more than 2 seconds it cancels the previous request and call it again? I found some code and the timeoutInterval setting but I don't know how to call the function again based on it, and on the code I found it would just work like "let opt = HTTP(req)" ( https://github.com/daltoniam/SwiftHTTP/issues/177 ) so I don't know how to change to a GET or POST... Would be there any way to do it?

    Thanks in advance :)

    opened by matheuztavarez 8
  • Library load error in Xcode 6.4

    Library load error in Xcode 6.4

    I only add SwiftHTTP in Podfile and when I compile my workspace. It make library load error. This is my Podfile content

    platform :osx, '10.9'
    
    use_frameworks!
    
    target 'Nyaa.swift' do
    
      pod 'SwiftHTTP', '0.9.5'
    
    end
    
    

    When I check loading library of SwiftHTTP with otool.

        @rpath/libswiftAppKit.dylib (compatibility version 0.0.0, current version 0.0.0)
        @rpath/libswiftCore.dylib (compatibility version 0.0.0, current version 0.0.0)
        @rpath/libswiftCoreGraphics.dylib (compatibility version 0.0.0, current version 0.0.0)
        @rpath/libswiftDarwin.dylib (compatibility version 0.0.0, current version 0.0.0)
        @rpath/libswiftDispatch.dylib (compatibility version 0.0.0, current version 0.0.0)
        @rpath/libswiftFoundation.dylib (compatibility version 0.0.0, current version 0.0.0)
        @rpath/libswiftObjectiveC.dylib (compatibility version 0.0.0, current version 0.0.0)
        @rpath/libswiftQuartzCore.dylib (compatibility version 0.0.0, current version 0.0.0)
        @rpath/libswiftSecurity.dylib (compatibility version 0.0.0, current version 0.0.0)
    

    and Xcode error code is caused by loading swift runtime library.

    dyld: Library not loaded: @rpath/libswiftAppKit.dylib
      Referenced from: /Users/Luavis/Projects/Nyaa.swift/build/Debug/SwiftHTTP.framework/Versions/A/SwiftHTTP
      Reason: image not found
    

    Is there any solution for this problem?

    p.s. It run in mac command line tool project.

    opened by Luavis 8
  • SSL Pinning - Always failing

    SSL Pinning - Always failing

    What's the problem?

    Trying to load a self signed certificate like so:

        if let certPath = Bundle.module.url(forResource: "theCert", withExtension: "cer") {
                let certData = try! Data(contentsOf: certPath)
                let cert = SSLCert(data: certData)
                task.security = HTTPSecurity(certs: [cert], usePublicKeys: false)
    }
    
     task.run { (response) in
                if let err = response.error {
                    print("error: \(err)")
                    return
                }
    
           // Do work
    }
    

    I have also tried using the SecKey initializer and even though I get back a valid value, pinning always fails. The task is canceled and I'm not sure why.

    Can you lead me in the right direction? Thank you for your time.

    opened by nilecoder 0
  • Make SwiftHTTP be consumable as a Swift package

    Make SwiftHTTP be consumable as a Swift package

    This fleshes out the package file with things needed to be able to run swift build and swift test. Tests were made compilable or removed where the tested functionality didn't exist anymore.

    Fixes #306

    opened by Johennes 0
  • Cannot consume as Swift package

    Cannot consume as Swift package

    The provided Package.swift file is insufficient for consuming SwiftHTTP as a Swift package in another project. It doesn't include the minimum Swift tools version and defines no build products.

    opened by Johennes 0
  • 'taskMap' Dictionary related crashes in Operation.swift file

    'taskMap' Dictionary related crashes in Operation.swift file

    What is expected Crashes should not happen

    Describe the bug The crash occurs infrequently when either a new HTTP request is created or handle a finishing task. From my observation, the crash occurs on performing operations like get, set, remove on the dictionary 'taskMap' in DelegateManager class. There could be a race condition. I installed SwiftHTTP 3.0.1 using CocoaPods. Kindly let me know how to rectify this based on the info below.

    This is the code the creates the HTTP request private func createRequest(with method: HTTPVerb, at uri: String, parameters: HTTPParameterProtocol?, headers: [String: String]?, requestSerializer _: HTTPSerializeProtocol, completionHandler: ((Response) -> Void)? = nil) -> HTTP? {

    return HTTP.New(uri, method: method, parameters: parameters, headers: headers, requestSerializer: JSONParameterSerializer(), completionHandler: completionHandler)

    }

    The different crashes are shared below: 1. SwiftHTTP: specialized Dictionary.Variant.setValue(:forKey:)

    Date/Time:           2020-06-26 17:01:40.2537 -0700
    Launch Time:         2020-06-26 17:01:39.0913 -0700
    OS Version:          iPhone OS 13.5.1 (17F80)
    Release Type:        User
    Baseband Version:    5.60.01
    Report Version:      104
    
    Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
    Exception Subtype: KERN_INVALID_ADDRESS at 0x8000000000000008
    VM Region Info: 0x8000000000000008 is not in any region.  Bytes after previous region: 9223372025580486665  
          REGION TYPE                      START - END             [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
          MALLOC_NANO            0000000280000000-00000002a0000000 [512.0M] rw-/rwx SM=PRV  
    --->  
          UNUSED SPACE AT END
    
    Termination Signal: Segmentation fault: 11
    Termination Reason: Namespace SIGNAL, Code 0xb
    Terminating Process: exc handler [1271]
    Triggered by Thread:  8
    
    Thread 8 name:
    Thread 8 Crashed:
    0   libswiftCore.dylib            	0x00000001b52744a0 swift_isUniquelyReferenced_nonNull_native + 0 (SwiftObject.mm:1361)
    1   SwiftHTTP                     	0x0000000107c0e8e4 specialized Dictionary._Variant.setValue(_:forKey:) + 48
    2   SwiftHTTP                     	0x0000000107c0b600 HTTP.init(_:session:isDownload:) + 364 (Operation.swift:0)
    3   SwiftHTTP                     	0x0000000107c0f780 specialized static HTTP.New(_:method:parameters:headers:requestSerializer:completionHandler:) + 844 (Operation.swift:0)
    4   SwiftHTTP                     	0x0000000107c0b744 static HTTP.GET(_:parameters:headers:requestSerializer:completionHandler:) + 44
    5   XYZAPP                  	        0x0000000104f67e2c NetworkCall.get(from:parameters:with:failureHandler:) + 548 (NetworkCall.swift:32)
    6   XYZAPP                   	        0x00000001052813b0 AppConfigurationService.checkIfUpdatesAreNeeded(completionHandler:errorHandler:) + 1824 (AppConfigurationService.swift:48)
    7   XYZAPP                   	        0x0000000105280a0c closure #1 in AppConfigurationService.updateResourceBundleIfNeeded() + 392 (AppConfigurationService.swift:25)
    8   XYZAPP                   	        0x0000000104e982a0 thunk for @escaping @callee_guaranteed () -> () + 56 (<compiler-generated>:0)
    9   libdispatch.dylib             	0x00000001a77aa9a8 _dispatch_call_block_and_release + 24 (init.c:1408)
    10  libdispatch.dylib             	0x00000001a77ab524 _dispatch_client_callout + 16 (object.m:495)
    11  libdispatch.dylib             	0x00000001a779165c _dispatch_root_queue_drain + 640 (inline_internal.h:2484)
    12  libdispatch.dylib             	0x00000001a7791cd0 _dispatch_worker_thread2 + 112 (queue.c:6628)
    13  libsystem_pthread.dylib       	0x00000001a77fcb38 _pthread_wqthread + 212 (pthread.c:2364)
    14  libsystem_pthread.dylib       	0x00000001a77ff740 start_wqthread + 8
    

    2. SwiftHTTP: specialized Dictionary._Variant.removeValue(forKey:)

    Date/Time:           2020-07-01 22:33:23.9266 -0500
    Launch Time:         2020-07-01 22:33:22.2928 -0500
    OS Version:          iPhone OS 13.5.1 (17F80)
    Release Type:        User
    Baseband Version:    3.05.00
    Report Version:      104
    
    Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
    Exception Subtype: KERN_INVALID_ADDRESS at 0x8000000000000028
    VM Region Info: 0x8000000000000028 is not in any region.  Bytes after previous region: 9223372025580486697  
          REGION TYPE                      START - END             [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
          MALLOC_NANO            0000000280000000-00000002a0000000 [512.0M] rw-/rwx SM=PRV  
    --->  
          UNUSED SPACE AT END
    
    Termination Signal: Segmentation fault: 11
    Termination Reason: Namespace SIGNAL, Code 0xb
    Terminating Process: exc handler [1402]
    Triggered by Thread:  6
    
    Thread 6 name:
    Thread 6 Crashed:
    0   SwiftHTTP                     	0x000000010572df2c specialized Dictionary._Variant.removeValue(forKey:) + 40
    1   SwiftHTTP                     	0x00000001057300f8 specialized DelegateManager.urlSession(_:task:didCompleteWithError:) + 892 (<compiler-generated>:0)
    2   SwiftHTTP                     	0x00000001057300f8 specialized DelegateManager.urlSession(_:task:didCompleteWithError:) + 892 (<compiler-generated>:0)
    3   SwiftHTTP                     	0x000000010572c050 @objc DelegateManager.urlSession(_:task:didCompleteWithError:) + 104 (<compiler-generated>:0)
    4   XYZAPP                  	        0x0000000102f7a038 __InstrumentURLSessionTaskDidCompleteWithError_block_invoke + 240
    5   CFNetwork                     	0x000000019bc10234 __51-[NSURLSession delegate_task:didCompleteWithError:]_block_invoke.194 + 648 (Session.mm:692)
    6   Foundation                    	0x0000000198be83f0 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 16 (NSOperation.m:1541)
    7   Foundation                    	0x0000000198af3710 -[NSBlockOperation main] + 84 (NSOperation.m:1560)
    8   Foundation                    	0x0000000198bea64c __NSOPERATION_IS_INVOKING_MAIN__ + 20 (NSOperation.m:2184)
    9   Foundation                    	0x0000000198af3414 -[NSOperation start] + 740 (NSOperation.m:2201)
    10  Foundation                    	0x0000000198beb044 __NSOPERATIONQUEUE_IS_STARTING_AN_OPERATION__ + 20 (NSOperation.m:2215)
    11  Foundation                    	0x0000000198beab10 __NSOQSchedule_f + 180 (NSOperation.m:2226)
    12  libdispatch.dylib             	0x00000001984cadd0 _dispatch_block_async_invoke2 + 104 (queue.c:525)
    13  libdispatch.dylib             	0x00000001984e7524 _dispatch_client_callout + 16 (object.m:495)
    14  libdispatch.dylib             	0x00000001984c1274 _dispatch_continuation_pop$VARIANT$armv81 + 404 (inline_internal.h:2484)
    15  libdispatch.dylib             	0x00000001984c09e8 _dispatch_async_redirect_invoke + 584 (queue.c:803)
    16  libdispatch.dylib             	0x00000001984cd534 _dispatch_root_queue_drain + 344 (inline_internal.h:2525)
    17  libdispatch.dylib             	0x00000001984cdcd0 _dispatch_worker_thread2 + 112 (queue.c:6628)
    18  libsystem_pthread.dylib       	0x0000000198538b38 _pthread_wqthread + 212 (pthread.c:2364)
    19  libsystem_pthread.dylib       	0x000000019853b740 start_wqthread + 8
    

    3. SwiftHTTP: specialized NativeDictionary.mutatingFind(:isUnique:)

    Date/Time:           2020-07-03 14:00:18.1024 -0400
    Launch Time:         2020-07-03 14:00:17.2042 -0400
    OS Version:          iPhone OS 13.5.1 (17F80)
    Release Type:        User
    Baseband Version:    2.06.00
    Report Version:      104
    
    Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
    Exception Subtype: KERN_INVALID_ADDRESS at 0x8000000000000028 -> 0x0000000000000028 (possible pointer authentication failure)
    VM Region Info: 0x28 is not in any region.  Bytes before following region: 4370776024
          REGION TYPE                      START - END             [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
          UNUSED SPACE AT START
    --->  
          __TEXT                 000000010484c000-0000000104884000 [  224K] r-x/r-x SM=COW  .../XYZApp
    
    Termination Signal: Segmentation fault: 11
    Termination Reason: Namespace SIGNAL, Code 0xb
    Terminating Process: exc handler [625]
    Triggered by Thread:  2
    
    Thread 2 name:
    Thread 2 Crashed:
    0   SwiftHTTP                     	0x0000000107f769b8 specialized _NativeDictionary.mutatingFind(_:isUnique:) + 40
    1   SwiftHTTP                     	0x0000000107f76908 specialized Dictionary._Variant.setValue(_:forKey:) + 84
    2   SwiftHTTP                     	0x0000000107f76908 specialized Dictionary._Variant.setValue(_:forKey:) + 84
    3   SwiftHTTP                     	0x0000000107f73600 HTTP.init(_:session:isDownload:) + 364 (Operation.swift:0)
    4   SwiftHTTP                     	0x0000000107f77780 specialized static HTTP.New(_:method:parameters:headers:requestSerializer:completionHandler:) + 844 (Operation.swift:0)
    5   XYZApp                       	0x00000001050e5790 NetworkResource.createRequest(with:at:parameters:headers:requestSerializer:completionHandler:) + 232 (NetworkResource.swift:143)
    6   XYZApp                      	0x00000001050e3e78 NetworkResource.get(at:parameters:resourceHandler:resourceArrayHandler:failureHandler:) + 708 (NetworkResource.swift:32)
    7   XYZApp                      	0x000000010505f3c4 UTMTrackingService.getAffiliateInfo(completion:failure:) + 1240 (UTMTrackingService.swift:97)
    8   XYZApp                      	0x00000001050eefc0 closure #4 in AppDelegate.application(_:willFinishLaunchingWithOptions:) + 96 (AppDelegate.swift:114)
    9   XYZApp                      	0x00000001052002a0 thunk for @escaping @callee_guaranteed () -> () + 56 (<compiler-generated>:0)
    10  libdispatch.dylib             	0x00000001b89a6ec4 _dispatch_call_block_and_release + 32 (init.c:1408)
    11  libdispatch.dylib             	0x00000001b89a833c _dispatch_client_callout + 20 (object.m:495)
    12  libdispatch.dylib             	0x00000001b89b76e8 _dispatch_root_queue_drain + 644 (inline_internal.h:2484)
    13  libdispatch.dylib             	0x00000001b89b7d9c _dispatch_worker_thread2 + 116 (queue.c:6628)
    14  libsystem_pthread.dylib       	0x00000001b8a0f6d8 _pthread_wqthread + 216 (pthread.c:2364)
    15  libsystem_pthread.dylib       	0x00000001b8a159c8 start_wqthread + 8
    

    4. SwiftHTTP: specialized Dictionary.subscript.getter

    Date/Time:           2020-07-04 14:39:11.9177 -0400
    Launch Time:         2020-07-04 14:39:10.6587 -0400
    OS Version:          iPhone OS 13.5.1 (17F80)
    Release Type:        User
    Baseband Version:    1.06.00
    Report Version:      104
    
    Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
    Exception Subtype: KERN_INVALID_ADDRESS at 0x8000000000000010 -> 0x0000000000000010 (possible pointer authentication failure)
    VM Region Info: 0x10 is not in any region.  Bytes before following region: 4364894192
          REGION TYPE                      START - END             [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
          UNUSED SPACE AT START
    --->  
          __TEXT                 00000001042b0000-00000001042e8000 [  224K] r-x/r-x SM=COW  .../XYZApp
    
    Termination Signal: Segmentation fault: 11
    Termination Reason: Namespace SIGNAL, Code 0xb
    Terminating Process: exc handler [12446]
    Triggered by Thread:  9
    
    Thread 9 name:
    Thread 9 Crashed:
    0   SwiftHTTP                     	0x00000001079cbaec specialized Dictionary.subscript.getter + 12 (<compiler-generated>:0)
    1   SwiftHTTP                     	0x00000001079cb598 HTTP.init(_:session:isDownload:) + 260 (Operation.swift:365)
    2   SwiftHTTP                     	0x00000001079cb598 HTTP.init(_:session:isDownload:) + 260 (Operation.swift:365)
    3   SwiftHTTP                     	0x00000001079cf780 specialized static HTTP.New(_:method:parameters:headers:requestSerializer:completionHandler:) + 844 (Operation.swift:0)
    4   SwiftHTTP                     	0x00000001079cb744 static HTTP.GET(_:parameters:headers:requestSerializer:completionHandler:) + 44
    5   XYZApp                      	0x0000000104d33e2c NetworkCall.get(from:parameters:with:failureHandler:) + 548 (NetworkCall.swift:32)
    6   XYZApp                      	0x000000010504d3b0 AppConfigurationService.checkIfUpdatesAreNeeded(completionHandler:errorHandler:) + 1824 (AppConfigurationService.swift:48)
    7   XYZApp                      	0x000000010504ca0c closure #1 in AppConfigurationService.updateResourceBundleIfNeeded() + 392 (AppConfigurationService.swift:25)
    8   XYZApp                      	0x0000000104c642a0 thunk for @escaping @callee_guaranteed () -> () + 56 (<compiler-generated>:0)
    9   libdispatch.dylib             	0x0000000191012ec4 _dispatch_call_block_and_release + 32 (init.c:1408)
    10  libdispatch.dylib             	0x000000019101433c _dispatch_client_callout + 20 (object.m:495)
    11  libdispatch.dylib             	0x00000001910236e8 _dispatch_root_queue_drain + 644 (inline_internal.h:2484)
    12  libdispatch.dylib             	0x0000000191023d9c _dispatch_worker_thread2 + 116 (queue.c:6628)
    13  libsystem_pthread.dylib       	0x000000019107b6d8 _pthread_wqthread + 216 (pthread.c:2364)
    14  libsystem_pthread.dylib       	0x00000001910819c8 start_wqthread + 8
    
    opened by rahul4moonlight 2
  • SSL Pinning  - Code=-999

    SSL Pinning - Code=-999 "cancelled"

    Hi,

    I tried implementing the SSL Pinning configuring the DER certification into the bundle.

    I'm getting an error

    <1> load failed with error Error Domain=NSURLErrorDomain Code=-999 "cancelled"

    _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<1>, NSLocalizedDescription=cancelled} [-999] 2019-03-02 09:33:07.177513+0530 aaa[6110:2098149] Task .<1> finished with error - code: -999

    Please help on this.

    opened by elango 1
Owner
Dalton
Developer. Disciple. Computer science aficionado. Mobile enthusiast. Drum machine. Rock climbing extraordinaire. The next American Ninja Warrior.
Dalton
Easy HTTP Networking in Swift a NSURLSession wrapper with image caching support

Networking was born out of the necessity of having a simple networking library that doesn't have crazy programming abstractions or uses the latest rea

Nes 1.3k Dec 17, 2022
πŸ€΅πŸ½β€β™€οΈ Janet β€” A thin HTTP networking layer built on URLSession for simple, declarative endpoint specification leveraging the power of async/await.

????‍♀️ Janet β€” Just another networking kit β€” A thin HTTP networking layer built on URLSession for simple, declarative endpoint specification leveragi

Niklas Holloh 3 Sep 6, 2022
Easy to use CFNetwork wrapper for HTTP requests, Objective-C, Mac OS X and iPhone

ASIHTTPRequest is an easy to use wrapper around the CFNetwork API that makes some of the more tedious aspects of communicating with web servers easier

Ben Copsey 5.8k Dec 14, 2022
NSURLSession network abstraction layer, using Codable and Decodable for response and Encodable for request. βš™οΈπŸš€

SONetworking NSURLSession network abstraction layer, using Codable and Decodable for response and Encodable for request. Project Folder and File Struc

Ahmad AlSofi 4 Jan 28, 2022
A modern download manager based on NSURLSession to deal with asynchronous downloading, management and persistence of multiple files.

TWRDownloadManager TWRDownloadManager A modern download manager for iOS (Objective C) based on NSURLSession to deal with asynchronous downloading, man

Michelangelo Chasseur 407 Nov 19, 2022
A frida tool that capture GET/POST HTTP requests of iOS Swift library 'Alamofire' and disable SSL Pinning.

FridaHookSwiftAlamofire A frida tool that capture GET/POST HTTP requests of iOS Swift library 'Alamofire' and disable SSL Pinning. δΈ­ζ–‡ζ–‡ζ‘£εŠθΏ‡η¨‹ Features Ca

neilwu 69 Dec 16, 2022
Menet is a TCP network middleware that can be dynamically modified through HTTP requests.

Menet Menet is a TCP network middleware that can be dynamically modified through HTTP requests. This is an experimental project, do NOT use it in prod

Nik 2 May 19, 2022
Http - Demo for Http Layer

http Example To run the example project, clone the repo, and run pod install fro

null 0 Jan 24, 2022
A glorious Swift wrapper around NSNotificationCenter

Kugel A glorious Swift wrapper around NSNotificationCenter. ⚠️ Deprecated ⚠️ This library is deprecated and will not be maintained anymore. With Swift

Scoop 75 Sep 22, 2022
A testable RxSwift wrapper around MultipeerConnectivity

A testable RxSwift wrapper around MultipeerConnectivity

RxSwift Community 69 Jul 5, 2022
A Combine-style wrapper around Network's NWConnection with a UDP protocol

A Combine-style wrapper around Network's NWConnection with a UDP protocol

Emlyn Bolton 3 Sep 26, 2022
Http Request wrapper written in Swift

Net Net is a HttpRequest wrapper written in Swift Features GET, POST, PUT, DELETE method Powerful request params: nested params, number, string, dic,

Le Van Nghia 304 Jun 29, 2022
Approov Integration Examples 0 Jan 26, 2022
Request adapter for URL requests from "MovieLister" demo app (Swift for Good book, a chapter by Ben Scheirman)

RequestAdapter Request adapter for URL requests from "MovieLister" demo app (Swift for Good book, a chapter by Ben Scheirman) The code is taken from:

Mihaela Mihaljevic Jakic 0 Nov 22, 2021
🌸 Powerful Codable API requests builder and manager for iOS.

This lib is about network requests with blackjack, roulette and craps! Using it you will be able to convert your massive API layer code into an awesom

CodyFire 251 Jan 8, 2023
a NSURLCache subclass for handling all web requests that use NSURLRequest

EVURLCache What is this? This is a NSURLCache subclass for handeling all web requests that use NSURLRequest. (This includes UIWebView) The EVURLCache

Edwin Vermeer 296 Dec 18, 2022
Synchronous requests for AFNetworking 1.x, 2.x, and 3.x

AFNetworking-Synchronous A minimal category which extends AFNetworking to support synchronous requests. Usage 3.x pod 'AFNetworking', '~> 3.0' pod

Paul Melnikow 160 Dec 7, 2022
CoreNetwork module with the basic functionality of requests to the network

CoreNetwork module with the basic functionality of requests to the network

Moscow Metro 4 Apr 27, 2022
VFNetwork is a protocol-oriented network layer that will help you assemble your requests in just a few steps.

Simple, Fast and Easy. Introduction VFNetwork is a protocol-oriented network layer that will help you assemble your requests in just a few steps. How

Victor Freitas 4 Aug 22, 2022