• Stars
    star
    302
  • Rank 138,030 (Top 3 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 10 years ago
  • Updated about 9 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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, array, image, data
  • Json, Image, Xml Response
  • Download file: resume, suspend, cancel
  • Upload file, data, params(multi-part)
  • Progress closure
  • Background donwload, upload
  • Authentication
  • Batch of operations
  • BaseURL
  • Customizable header

Demo app

screenshot

Usage

Use one of the following methods to create a Net instance

// without baseURL
let net = Net()

// with baseURL
let net = Net(baseUrlString: "http://www.puqiz.com/") 

HttpRequest

GET Request
let url = "get_path"
let params = ["integerNumber": 1, "doubleNumber": 2.0, "string": "hello"]

net.GET(url, params: params, successHandler: { responseData in
		let result = responseData.json(error: nil)
		NSLog("result \(result)")
	}, failureHandler: { error in
		NSLog("Error")
	})

// you can also make a request with absolute url
let url = "http://www.puqiz.com/get_path"
net.GET(absoluteUrl: url, params: params, successHandler: { responseData in
		let result = responseData.json(error: nil)
		NSLog("result \(result)")
	}, failureHandler: { error in
		NSLog("Error")
	})

You can also use nested params

// nested params
let params = ["string": "test",
            "integerNumber": 1,
            "floatNumber": 1.5,
            "array": [10, 20, 30],
            "dictionary": ["x": 100.0, "y": 200.0],
            "image": NetData(pngImage: img, filename: "myIcon")]

By using responseData in sucessHandler closure you can quickly

  • get json dictionary
  • get image
  • parse xml

for GET, POST, PUT, DELETE request.

// get json dictionary from response data
let jsonDic = responseData.json(error: error)

// get image from response data
let image = responseData.image()

// parse xml with delegate
let result = responseData.parseXml(delegate: self)
POST Request

Net will automatically check your params to send request as a URL-Encoded request or a Multi-Part request. So you can easily post with number, string, image or binary data.

  • URL-Encoded Request
let url = "post_path"
let params = ["string": "test", "integerNumber": 1, "floatNumber": 1.5]
        
net.POST(url, params: params, successHandler: { responseData in
		let result = responseData.json(error: nil)
		NSLog("result: \(result)")
	}, failureHandler: { error in
		NSLog("Error")
	})
  • Multi-Part Request
let url = "post_path"
let img = UIImage(named: "puqiz_icon")
        
let params = ["string": "test", "integerNumber": 1,
            "icon": NetData(pngImage: img, filename: "myIcon")]
        
net.POST(url, params: params, successHandler: { responseData in
		let result = responseData.json(error: nil)
		NSLog("result: \(result)")
	}, failureHandler: { error in
		NSLog("Error")
	})
PUT Request
let url = "put_path"
let params = ["string": "test", "integerNumber": 1, "floatNumber": 1.5]
        
net.PUT(url, params: params, successHandler: { responseData in
		let result = responseData.json(error: nil)
		NSLog("result: \(result)")
	}, failureHandler: { error in
		NSLog("Error")
	})
DELETE Request
let url = "delete_path"
let params = ["id": 10]
        
net.DELETE(url, params: params, successHandler: { responseData in
		NSLog("result: \(result)")
	}, failureHandler: { error in
		NSLog("Error")
	})

Task

Before using download/upload function you have to call setupSession method to setup the session.

// setup session without backgroundIdentifier
net.setupSession()

To perform background downloads or uploads, you have to call setupSession method with a background identifier string. Then your download/upload tasks can be run even when the app is suspended, exits or crashes.

// setup session with backgroundIdentifier
net.setupSession(backgroundIdentifier: "com.nghialv.download")

// you can set eventsForBackgroundHandler closure
// this closure will be invoked when a task is completed in the background
net.eventsForBackgroundHandler = { urlSession in
		urlSession.getDownloadingTasksCount{ downloadingTaskCount in
		if downloadingTaskCount == 0 {
			NSLog("All files have been downloaded!")
		}
	}
}
Download
let downloadTask = net.download(absoluteUrl: url, progress: { progress in
		NSLog("progress \(progress)")
	}, completionHandler: { fileUrl, error in
		if error != nil {
			NSLog("Download failed")
		}
		else {
			NSLog("Downloaded to  : \(fileUrl)")
		}
	})

// you can control your task
downloadTask.resume()
downloadTask.suspend()
downloadTask.cancel()
Upload
  • Upload with file path
let task = net.upload(absoluteUrl: url, fromFile: file, progressHandler: { progress in
		NSLog("progress \(progress)")
	}, completionHandler: { error in
		if error != nil {
			NSLog("Upload failed : \(error)")
		}
		else {
			NSLog("Upload completed")
		}
	})
  • Upload with data
let yourData = NSData(...)
        
net.upload(absoluteUrl: url, data: yourData, progressHandler: { progress in
		NSLog("progress: \(progress)")
	}, completionHandler: { error in
		NSLog("Upload completed")
	})
  • Upload with params
let image = UIImage(named: "image_file")
let imageData = UIImagePNGRepresentation(image)
let params = ["number": 1, "string": "net", "data": imageData]

net.upload(absoluteUrl: imgUrl, params: params, progressHandler: { progress in
		NSLog("progress: \(progress)")
	}, completionHandler: { error in
		NSLog("Upload completed")
	})

By default, the upload task will be performed as POST method and

  • Content-Type = application/octet-stream (upload with file or data)
  • Content-Type = multipart/form-data (upload with params)

But you can configure the upload task before resuming.

// set method
yourUploadTask.setHttpMethod(.PUT)

// set header field
yourUploadTask.setValue(value: "your_value", forHttpHeaderField: "header_field")

Integration

Just drag Net folder to the project tree

More Repositories

1

MaterialKit

Material design components for iOS written in Swift
Swift
2,504
star
2

promviz

Visualize the traffic of your clusters in realtime from Prometheus data
Go
955
star
3

Hakuba

🌸 Cellmodel-driven tableview manager
Swift
474
star
4

Transporter

A tiny library makes uploading and downloading easier
Swift
452
star
5

Sapporo

Cellmodel-driven collectionview manager
Swift
246
star
6

Future

Swift µframework providing Future<T, Error>
Swift
122
star
7

GCD

A wrapper of Grand Central Dispatch written in Swift
Swift
72
star
8

Try

Swift µframework providing Try<T>
Swift
32
star
9

openGL-tankgame

A simple 3D game using openGL
C++
23
star
10

TVDataSource

datasource class for uitableview
Objective-C
17
star
11

gamegl

the bottom part of puzzle dragon game using OpenglES (without any framework)
Objective-C
14
star
12

iBall

iPhone, iPad間のバトルゲーム (OpenGLES)
C
6
star
13

VersionTracker

Tracking the app version
Swift
4
star
14

clibs

Central repository containing C libraries for testing
C
3
star
15

opencv-optical-flow

OpenCV, Python
Python
3
star
16

xcode_project_templates

xcode project templates
Objective-C
3
star
17

Kinect-ARToolKit

some simple examples of using Kinect (OpenNI) and ARToolKit
C++
2
star
18

vlcamera

vlcamera app
Objective-C
2
star
19

funnytext

render text in some shapes, change the position and orientation of each character
Objective-C
2
star
20

opencv_ios

opencv (face, eyes... tracking)
1
star
21

nghialv.github.com

my blog
HTML
1
star
22

flex-bison-cpp

a simple example of flex, bison
C++
1
star
23

tomojisho

a facebook game which looks like a dictionary for your friends. Through this game, you can review the information of your friends
PHP
1
star
24

rubyss

ruby shell script
Ruby
1
star