Giter Club home page Giter Club logo

swifthttp's Introduction

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

swifthttp's People

Contributors

aamirr avatar acmacalister avatar bpollman avatar daltoniam avatar fform avatar jrschifa avatar keith avatar mogadget avatar neichen avatar nemesis avatar pizthewiz avatar rajeev avatar randomite avatar readmecritic avatar rere61 avatar robertmryan avatar robintemme avatar samlbest avatar serendipityapps avatar theadam avatar yoneapp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swifthttp's Issues

Multiple file downloads

I was tinkering with the library and I wanted to share, off the top of my head, my own implementation of multiple file downloads using multiple downloadTasks with the same background Session. Not sure if this is kosher though.

public func downloadMultiple(urls: Array<String>, parameters: Dictionary<String,AnyObject>?,progress:((Double) -> Void)!, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) -> [String:NSURLSessionDownloadTask?] {

    var tasks = Dictionary<String,NSURLSessionDownloadTask>()
    let ident = createBackgroundIdent()
    let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(ident)
    let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)

    for url in urls {

        let serialReq = createRequest(url,method: .GET, parameters: parameters)
        if serialReq.error != nil {
            failure(serialReq.error!, nil)
            tasks[url] = nil
         }

        let task = session.downloadTaskWithRequest(serialReq.request)
        let taskId = ident + "-" + String(task.taskIdentifier)
        self.backgroundTaskMap[taskId] = BackgroundBlocks(success,failure,progress)
        task.resume()
        tasks[url] = task
    }

    return tasks
}

Let me know what you think. I can put that into a pull request.

If credentials wrong, HTTPTask will try to use incorrect credentials repeatedly

Pursuant to http://stackoverflow.com/q/27949677/1271826, the didReceiveChallenge should probably only try a particular set of credentials once. If they were wrong, the existing implementation would try repeatedly.

Therefore, I might suggest changing:

public func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
    if let a = auth {
        let cred = a(challenge)
        if let c = cred {
            completionHandler(.UseCredential, c)
            return
        }
        completionHandler(.RejectProtectionSpace, nil)
        return
    }
    completionHandler(.PerformDefaultHandling, nil)
}

To:

public func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
    if let credential = auth?(challenge) {
        if challenge.previousFailureCount == 0 {
            completionHandler(.UseCredential, credential)
        } else {
            completionHandler(.RejectProtectionSpace, nil)
        }
    } else {
        completionHandler(.PerformDefaultHandling, nil)
    }
}

This will only try using the credentials provided once.

Error While attempting to use Cocoapods, not sure what to do.

Error

SyntaxError - /Users/<mycomp>/Desktop/iPhone Dev/<projectFolder>/Podfile:6: syntax error, unexpected tCONSTANT, expecting end-of-input
pod 'SwiftHTTP', :git => "https://github.co...
              ^
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:254:in `eval'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:254:in `block in from_ruby'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:51:in `instance_eval'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:51:in `initialize'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:251:in `new'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:251:in `from_ruby'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:227:in `from_file'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.0/lib/cocoapods/config.rb:176:in `podfile'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.0/lib/cocoapods/command.rb:109:in `verify_podfile_exists!'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.0/lib/cocoapods/command/project.rb:100:in `run'
/Library/Ruby/Gems/2.0.0/gems/claide-0.8.1/lib/claide/command.rb:312:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.0/lib/cocoapods/command.rb:46:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.0/bin/pod:44:in `<top (required)>'
/usr/bin/pod:23:in `load'
/usr/bin/pod:23:in `<main>'

[!] Oh no, an error occurred.

It appears to have originated from your Podfile at line 6.

Cannot uploading a file

Please, implement the file upload as soon as possible ! I (we) need it in this awesome library ! :D

get a array of json objects...

Hi I want to use swifthttp to get a array of returned json objects... Is this possible? I can't find a way to achieve this.. Here is what I got..

func requestAllCars() {
    var request = HTTPTask()
    let params: Dictionary<String, String> = ["apikey":apikey, "username":username]
    request.requestSerializer = JSONRequestSerializer()
    request.responseSerializer = JSONResponseSerializer()
    request.POST(url, parameters: params, success: {(response: HTTPResponse) in
        if let dict = response.responseObject as? Dictionary<String, String> {
            println("print the whole response: \(dict)")
            if let statusCode: AnyObject = dict["status"] {
                if statusCode as NSString == "Error" {
                    // Oops error

                    })
                }
            } else {


            }
        }
        }, failure: {(error: NSError, response: HTTPResponse?) in
            println("object not received \(error)")

            })
    })

}

Question about async

I'm trying to do a login and get the cookies from server.

func foo(username: String, password: String) -> Bool {
        var url = "http://example"
        var request = HTTPTask()
        var parameters = ["username": username, "password": password]
        var result = false;
        request.requestSerializer = JSONRequestSerializer()
        request.POST(url, parameters: parameters,
        success: {
            (response: HTTPResponse) in
            if response.responseObject != nil {
                result = true
            },
        }, failure: {(error: NSError) in
                println(" error \(error)")
        })
    return result;
}

Since its running async, my result always is false. Any suggestion of fixing it? Thanks.

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.

NSOperationQueue and maxConcurrentOperationCount

I have a problem with the NSOperationQueue example. There are only maxConcurrentOperationCount requests and all other requests will not called.

If I try this example, only Request one is called but not Request two. If I set maxConcurrentOperationCount to 2, both requests are called.

let operationQueue = NSOperationQueue()
operationQueue.maxConcurrentOperationCount = 1

var request = HTTPTask()
var opt = request.create("http://vluxe.io", method: .GET, parameters: nil, success: {(response: HTTPResponse) in
        println("Request one")
    },failure: {(error: NSError, response: HTTPResponse?) in
        println("error: \(error)")
})
if let o = opt {
    operationQueue.addOperation(o)
}

opt = request.create("http://vluxe.io", method: .GET, parameters: nil, success: {(response: HTTPResponse) in
        println("Request two")
    },failure: {(error: NSError, response: HTTPResponse?) in
        println("error: \(error)")
})
if let o = opt {
    operationQueue.addOperation(o)
}

Archiving an app fails

I'm trying to archive my app to submit to ITC for review. When I try and Archive, I get an error Could not build Objective-C module 'SwiftHTTP' I've cleared out my DerivedData and everything I can think of. Is there something wrong with this framework or am I just missing a step?

Problem with moveItemAtURL, when downloading Image

Hey @ all,

i have found an Issue, when you want to download an image from Webserver, and copy it from temp directory to documents directory:

This is the line, that have to replace:
let newPath = NSURL(string: "(paths[0])/(response.suggestedFilename!)")!
with:
NSURL(fileURLWithPath: "(path)/(fileName)")

because:
You want to move pathURL but newPath is not a FILEPATH (file://....)

So here is my code:

if response.responseObject != nil {
     let filePath = response.responseObject as? NSURL
     if let url = filePath {
         if let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String {
             if let fileName = response.suggestedFilename {
                 if let newPath = NSURL(fileURLWithPath: "\(path)/\(fileName)") {
                     let fileManager = NSFileManager.defaultManager()
                     fileManager.removeItemAtURL(newPath, error: nil)
                     fileManager.moveItemAtURL(url, toURL: newPath, error:nil)
                 }
             }
         }
     }
 }

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

playground

Do you know how to get this to work in the playground?

Download retry

Awesome job with the wrapper 👍
Just wondering if there would be any attempt in the future to support retried downloads for the download call like this

request.download(url: String, 
retries: Int /* number of retries */
parameters: Dictionary<String,AnyObject>?,
progress:((Double) -> Void)!, 
success:((HTTPResponse) -> Void)!, 
failure:((NSError, HTTPResponse?) -> Void)!)

It's useful to retry from the original call rather than calling the request.download from within the failure closure. May be there's a better way to do it :)

SwiftHTTP.framework is not shown in the Add framework dialog

From the SwiftHTTP documentation:
"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."

I only see the SwiftHTTPOSX.framework in the add framework dialog box, but not the SwiftHTTP.framework. The thing is I am developing an app for iOS...

I guess I may have done something wrong? What is the correct way to add the SwiftHTTP.xcodeproj to my iOS xCode project? Sorry I am new to this...

Compile error when using custom parameters

Using custom Dictionary object as parameter in GET request method, Xcode 6(6A313) shows this error

2014-09-17 10 04 58

If taking the same content as the parameter, then it goes well

2014-09-17 10 11 30

Hope someone can fix it

Authentication issue

Hello,

I am using SwiftHTTP to create an app for managing drupal 8 websites, the get requests work fine as they are accessable without authentication.
However, when I want to post new content to the site I'm getting an 403 error.
I can't find it in the code anywhere where the HTTPAuth class is even used to send the authentication credentials in a header (or whatever) to the server.

I just need a basic http authentication for this to work, but I guess it's not implemented? Or I am really blind. :p

Okay, so I found the implementation to URLSession, but I wounder why it's not working for me.

Added some println's to HTTPTask that don't get executed.
line 419 to check if it's calling the function and 423 to confirm.
Nothing prints

The delegate function URLSession for authentication never gets fired.

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

CocoaPods support

It would be nice to be able to include this library via CocoaPods!

How to save the cookie persistence

I have two button in test app, one is check the status of login and the second is login
1、I click the login button
2、The login status is true When I click the check button
3、Close the application and open again
4、The login status is false When I click the check button
We use sessionid in cookies to check login status in server

Please help a noob.

Can you please help a noob?

I would like to use swift to do what is described in this python script:

#coding: utf-8
# These code snippets use an open-source library. http://unirest.io/python
import requests

req = requests.request("POST","https://textanalysis.p.mashape.com/segmenter",
  headers={
           "X-Mashape-Key": "jhzbBPIPLImsh26lfMU4Inpx7kUPp1lzNbijsncZYowlZdAfAD",
           "Content-Type": "application/json"
           },
  params={
          "text":"这是中文测试"
          }
)
print req
print req.json()

Can you make an example using SwiftHTTP?

Request Synchronous

I have a problem, when I call request.GET but returned result after collectionView.reloadData

let result = Array()
let api: Api = Api()
self.result = api.getData()
self.collectionView.reloadData()

I thinks it can be solve by sync. please help me

properties not making through...

Hi. Good chance i'm missing something, but the given examples such as:

var request = HTTPTask()
request.baseURL = "http://api.someserver.com/1"
request.GET...

Don't work because each http method in the Task class, such as get, create a new HTTP task instead of using self.

func GET(url: Str... {
var task = HTTPTask()
task.run(url,method: .GET,parameters: parameters,success,failure)
}

So any property set in the first snippet, whether it be baseURL or a custom request serializer, don't get used. Am i missing something or should the second snippet NOT create a new Task() and instead use self?

Thanks!

Having difficulties to deploy to real machine

It works great on the simulator, but it crashes once I deployed to the real machine.

Environment: Maverick 10.9.5, Xcode 6.1, iOS 8.1

dyld: Library not loaded: @rpath/JSONJoy.framework/

I understand it quite different from compiling on the simulator (linking against the frameworks) verse on the real machine. Could you help me on this?

Thanks @daltoniam

Upload file - dataFromParameters function

Hi,
I'm getting an error when i'm trying to upload a file using file path.

This is the code i'm running:

let fileUrl = NSURL.fileURLWithPath("/Users/Marco/Documents/test.m4a")
var request = HTTPTask()

request.POST("http://www.example.com", parameters: ["p1": "v1", "p2": "v2", "file": HTTPUpload(fileUrl: fileUrl!)], success: {(response: HTTPResponse) -> Void in
            if response.responseObject != nil {
                let data = response.responseObject as NSData
                let str = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("response: \(str)")
            }
            },failure: {(error: NSError) -> Void in
                println(error)
 })

Then, from the 'HTTPRequestSerializer' class, from the 'dataFromParameters' function, I get an error in the following line:
mutData.appendData(upload.data!)
which prints: fatal error: unexpectedly found nil while unwrapping an Optional value

I suppose this is happening because the function is expecting a data blob file, which has a different constructor in HTTPUpload class.

convenience init(data: NSData, fileName: String, mimeType: String) {
        self.init()
        self.data = data
        self.fileName = fileName
        self.mimeType = mimeType
    }

xcode 6 beta 4

var UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileUrl?.pathExtension , nil);

Error : NSString is not a subtype of 'CFString'
FIle : HTTPUpload.swift

Headers

Any plans for adding headers to the request and also reading headers from the response?

[Error] Cannot convert the expression's type 'Dictionary<$T1,$T2>' to type 'Hashable'

I'm trying to convert the response to a dictionary (as specified in Readme example) but I'm getting this error while doing that.

Cannot convert the expression's type 'Dictionary<$T1,$T2>' to type 'Hashable'
var request = HTTPTask()
override func viewDidLoad() {
   super.viewDidLoad()
   // Do any additional setup after loading the view, typically from a nib.
   request.responseSerializer = JSONResponseSerializer()
}
@IBAction func fetchPollClicked(sender:UIButton) {
    request.GET("http://www.abc.com/api", parameters: nil, success: {(response: AnyObject?) -> Void in
       if response {
           let resp = response as Dictionary // Error in on this line
           println("response \(resp))")
         }
      }, failure: {(error: NSError) -> Void in
           println("error \(error)")
       })
  }

Api returns a deep nested JSON. What could be the issue?

two issues and a question

  1. var timeoutInterval: NSTimeInterval = 60
    i edited 60 to 10, but the timeout is always 60 sec.
  2. always into success block
    if request a 404, 403, 500 or any other statuscode's page, it always into success block, unless timeout into failure block.
  3. how to end an unclosed request ?
    if i open a viewcontroller, and the viewcontroller do a request, and i quit this viewcontroller or into another, but for some reasons (eg. network not good) the request is still requesting. so i want to know how to end an unclosed request.

thanks

Cannot convert the expression's type '()' to type 'Dictionary<String, String>

Im having issue with my test app.. my IBAction

    @IBAction func whenSigninIsTapped(sender : AnyObject) {
        var request = HTTPTask()
        request.requestSerializer = JSONRequestSerializer()
        request.responseSerializer = JSONResponseSerializer()
        request.POST("http://localhost:3000/api/v1/login", parameters:["email":"[email protected]","password":"password"],
            success: {(response: AnyObject?) -> Void in
                let resp = response as Dictionary<String,AnyObject>
            },failure: {(error: NSError) -> Void in

            })
    }

But it is causing a build failed with error Cannot convert the expression's type '()' to type 'Dictionary<String, String> specifically the line below

extraResponse.headers = hresponse.allHeaderFields as Dictionary<String,String>

It looks like a casting issue as allHeadersFields is a NSDictionary?

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

swift 1.2

Hello,

i have tried today to run my project on the new xcode 6.3 beta with swift 1.2, but i have seen that your project isn´t compatible with this swift version. For example i have to replace: var opt = self.create(url, method:.DELETE, parameters: parameters,success,failure) with var opt = self.create(url, method: .GET, parameters: parameters, success: success, failure: failure).

Example causes error in Xcode 6 beta 6.

var request = HTTPTask()
request.requestSerializer = JSONRequestSerializer()
request.responseSerializer = JSONResponseSerializer()
request.POST("http://" + self.host + "/authentication",parameters: ["email": self.username, "password": self.password], success: {
(response: HTTPResponse) -> Void in
  if response.responseObject {
    let dict = response.responseObject as Dictionary<String, AnyObject>
    println(dict)
  }
}, 
failure: {(error: NSError) -> Void in
  println(error)
})

Produces this error & Xcode's proposed fix:

screen shot 2014-08-20 at 8 49 14 pm

Xcode's fix compiles and works in simulator.

How do I get response URL?

I'm using POST to login and get a token that is in URL fragment (hash) after a bunch of redirects. How can I get final URL back from response object?

Response bodies ignored when HTTP statusCode > 299

Even though an HTTP status code may denote an error, APIs can still return valuable information in the body of the response (human readable messages for example). Currently there is no way to get access to the response in the failure handlers (as far as i can tell) even though when these error status codes are received the response is still created and its body parsed.

Authentication problem

Hi

I was using SwiftHTTP to create a Mac app for the website. I have my own REST API. Using the basic Auth, I have to send the request to some url to get the apikey.

import SwiftHTTP
var request = HTTPTask()
request.GET("https:[email protected]:[email protected]/api/v3/auth/token", parameters: nil, success: {(response: HTTPResponse) in
//code
}, failure: {(error: NSError, response: HTTPResponse?) in
//error
})

The url has to be sent in that format to get the apikey from the api. The GET request for normal domain like "http://github.com" was working. But for this kind of url's, I was getting an error like
error: Error Domain=HTTPTask Code=401 "accessed denied" UserInfo=0x600000234d80 {NSLocalizedDescription=accessed denied}.

Please help to overcome with this.

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.