Git Product home page Git Product logo

swift-srwebclient's Introduction

Swift-SRWebClient

A super simple http client framework for iOS and OSX in Swift.

Features

  1. Success and Failure closure blocks for easy callbacks.

  2. NSOperationQueue and NSBlockOperation to execute web requests, using which we can have a elegant way to set queuePriority, threadPriority, qualityOfService and cancel any particular Operation or all the Operations in OperationQueue.

  3. Provides function to send Image/multipart/form-data data.

  4. Function chaining provides us to chain methods and provides more expressive code to make web requests.

  5. Json deserialize, when any response is a valid JSON object, otherwise return the actaul response data as string.

  6. Headers, Timeout Interval can be set and controlled for each request.

  7. Test cases for all the functionalities

Success and Failure Closures

SRWebClient.GET("http://headers.jsontest.com/", 
	success:{(response:AnyObject!, status:Int) -> Void in 
		//process success response
	}, failure:{(error:NSError!) -> Void in 
		//process failure response
	})

NSBlockOperation

var webClient = SRWebClient(method: "POST", url:"http://validate.jsontest.com/")
webClient.timeoutInterval = 30.0
webClient.priority = NSOperationQueuePriority.High
webClient.send({(response:AnyObject!, status:Int) -> Void in
		//process success response
	}, failure:{(error:NSError!) -> Void in
        //process failure response        
	})

Image Upload

var image:UIImage = UIImage(named: "apple.jpeg")
let imageData:NSData = NSData.dataWithData(UIImageJPEGRepresentation(image, 1.0))
SRWebClient.POST("http://www.tiikoni.com/tis/upload/upload.php")
	.data(imageData, fieldName:"file", data:["days":"1","title":"Swift-SRWebClient","caption":"Uploaded via Swift-SRWebClient (https://github.com/sraj/Swift-SRWebClient)"])
	.send({(response:AnyObject!, status:Int) -> Void in
		//process success response
	},failure:{(error:NSError!) -> Void in
		//process failure response
	})

Function chaining

SRWebClient.POST("http://validate.jsontest.com")
	.headers(["Content-Type":"application/x-www-form-urlencoded charset=utf-8"])
	.data(["json":"[1, 2, 3]"])
	.send({(response:AnyObject!, status:Int) -> Void in
        	//process success response	        
		}, failure:{(error:NSError!) -> Void in
        	//process failure response    
		})

JSON Deserialize

SRWebClient.GET("http://headers.jsontest.com/", 
	success:{(response:AnyObject!, status:Int) -> Void in 
		let headersJSON = response! as Dictionary<String, String>
		println(headersJSON["key"]!)
	}, failure:{(error:NSError!) -> Void in 
		println(error!.code)
	})

Timeout Interval

var webClient = SRWebClient(method: "POST", url:"http://validate.jsontest.com/")
webClient.timeoutInterval = 60.0
webClient.headers(["key":"value"])
	.send({(response:AnyObject!, status:Int) -> Void in
        //process success response
	}, failure:{(error:NSError!) -> Void in
        //process failure response
	})

TODO

  • Retry mechanisam when a request fails.
  • Provide a more elegant way to cancel/suspend each operation.
  • Image download
  • Any features requested.

Contribution welcome!

License

The MIT License (MIT)

Copyright © 2014 Suman Raj Venkatesan

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Acknowledgment

Some API names are similar to Agent Framework. Licensed under MIT. Thanks to Christoffer Hallas for his contribution.

swift-srwebclient's People

Contributors

sraj 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swift-srwebclient's Issues

Supporting multipart/form-data `POST` request for uploading audio files with parametres.

I'm a JS developer new to swift cannot find any library that simply uploads the audio files with paramerts.

In js it's simple as bellow:

const uploadMedia = (
  file,
  schemaId,
  fields
) => {
  const body = new FormData()
  const data = new Blob(
      JSON.stringify({
        "key": "val",
       "key2: "val2"
    {
      type: 'application/json'
    }
  )
  body.set('data', data)
  body.append('media', file)

  return axios.post("https://exaple.url/post-audio", body)
}

Upload operation crashes on iPod Touch

Great library. Worked fine with quite an ease. However upload operation crashes when executed on an iPod touch. (Works fine on an iPhone and iPad.)

This is the place in a code where I am experiencing a crash :

var client = SRWebClient.POST('uploadURL')
client = client.headers([HMAC Headers dictionary])
client.data(imageData, fieldName : "file", data : [:]) -> Crashes right on this line
.send({(response:AnyObject!, status:Int) -> Void in

I checked in the debugger and NONE of the fields including imageData is nil. Still scratching my head around this crash.

Thanks,
Jayesh.

Latest beta

Hi there!
Would like to give this a try, but getting a few errors with the latest beta.
Any chance you could update it? 👍

Thanks!

Parsing json

I am using your library, I have to parse this json:

{"status":1,"picture":"78bd35ede6f1f996c2d05b54de5a6278.jpg"}

I tried this code:
let headersJSON = response! as! Dictionary<String, String>
println(headersJSON["picture"]!)

But I am getting following error:

Could not cast value of type '__NSCFString' (0x1036f2c50) to 'NSDictionary' (0x1036f38d0).

How can I fix it ?

Code=503 "The operation couldn’t be completed.

public func uploadImage(urlString:String, imageFile:UIImage, handler:(responseObject:AnyObject? , success: Bool?)-> Void) {
let imageData:NSData = UIImageJPEGRepresentation(imageFile, 1.0)
SRWebClient.POST(urlString)
.data(imageData, fieldName:"image", data:["apiKey":apiKey,"folder":folderName,"tags":tagNames])
.send({(response:AnyObject!, status:Int) -> Void in
println(status)
println(response)
handler(responseObject: response, success: true)
},failure:{(error:NSError!) -> Void in
println(error)
handler(responseObject: error, success: false)
})
}

Optional(<NSHTTPURLResponse: 0x7ff06053e8f0> { URL: http://img-cloud.herokuapp.com/upload } { status code: 503, headers {
"Cache-Control" = "no-cache, no-store";
Connection = "keep-alive";
"Content-Length" = 484;
"Content-Type" = "text/html; charset=utf-8";
Date = "Tue, 01 Sep 2015 10:49:40 GMT";
Server = Cowboy;
} })
Error Domain=/upload Code=503 "The operation couldn’t be completed. (/upload error 503.)"

Any Solution or anything I'm doing it wrong?

Support for Progress Bar?

Hi there,

Do you plan to support the ability to get progress on a download or upload so someone can hook it up to a UIProgressView?

Thanks,

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.