Http Request wrapper written in Swift

Related tags

Networking Net
Overview

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

Comments
  • I think there is a problem with content-length handling for some servers:

    I think there is a problem with content-length handling for some servers:

    In NetRequestSerialization.swift as a test, I took out the content length, and my php service only THEN parsed the content properly from a POST. Here is the snippit with the line commented out. I can look into this further if you want and make a patch if you want.

    The specification for post bodies is that if there is no formal content length specified, then the behavior is to read until EOF.

    PHP specifically did not parse the payload properly if content length was specified.

    if paramsData != nil { request.setValue(contentType, forHTTPHeaderField: "Content-Type") //request.setValue("(paramsData?.length)", forHTTPHeaderField: "Content-Length") request.HTTPBody = paramsData }

    opened by cryptomail 4
  • support for 192.168.*.*:port address?

    support for 192.168.*.*:port address?

    I can't make it work on my localhost ip address, but on web it works, what is problem?

            let net = Net(baseUrlString: "http://192.168.0.13:8000/rest/")
    
            let url = "entities/tablegroup/"
    
    opened by mirzadelic 2
  • GET request without parameters

    GET request without parameters

    I don't see a way of sending a get request without parameters. I can set params to a blank NSDictonary but that will still append a ?= to the url which in some REST API's will cause a failure. Is there a way to specify that there are no parameters.

    opened by shaungehring 2
  • Update for Xcode 6.1

    Update for Xcode 6.1

    • Utilize rawValue instead of toRaw() due to method being removed.
    • Fixes various compiler warnings surfacing in Xcode 6.1.

    More information in the Xcode 6.1 [release notes])(https://developer.apple.com/library/ios/releasenotes/DeveloperTools/RN-Xcode/Chapters/xc6_release_notes.html#//apple_ref/doc/uid/TP40001051-CH4-DontLinkElementID_23).

    opened by JonathanPorta 1
  • Update for Xcode 6 Beta 6

    Update for Xcode 6 Beta 6

    All updates are to keep compatible with the language changes in Beta 6.

    Net/NetDownloadTask.swift i commented out "Task == nil" Task does not conform to that and i did not know what to test for.

    opened by shaungehring 1
  • Factor out platform specific bits (UIImage)

    Factor out platform specific bits (UIImage)

    I noticed that there is not much in this library which prevents it from being cross platform, so I took a stab at factoring those things out (which was just UIImage).It now compiles for both iOS and OS X.

    Feel free to push back on this if you see any issues.

    opened by trenton42 0
  • Using session gives deprecation warning

    Using session gives deprecation warning

    When running upload/download tasks as part of a session I get the following notice:

    +backgroundSessionConfiguration: is deprecated. Please use +backgroundSessionConfigurationWithIdentifier: instead

    opened by chrisharrison 0
  • how can I show alert message after upload file

    how can I show alert message after upload file

    I want to show a message to tell user that uploading file is finished. But it did not show. The source is following. net.POST(url, params: params, successHandler: {responseData in let localNotification = UILocalNotification() localNotification.alertBody = "finished!" UIApplication.sharedApplication().presentLocalNotificationNow(localNotification) }, failureHandler: { error in // 失敗 let localNotification = UILocalNotification() localNotification.alertBody = "error!" UIApplication.sharedApplication().presentLocalNotificationNow(localNotification)

    })

    opened by luoganghua 0
  • [BC] success/failure callbacks for upload

    [BC] success/failure callbacks for upload

    Hello,

    PR replaces upload completionHandler with success/failure handlers similar to other requests signature. Also made callbacks optional. Due to changed signature of upload method this PR breaks existing code using upload

    opened by mente 0
  • eventsForBackgroundHandler does not receive events

    eventsForBackgroundHandler does not receive events

    I just downloaded your latest release and compile with no changes. I run the app, then select Download at the bottom of the screen. Next I select "Resume All". All 3 files are downloaded, and I see a 'Completion:' message for each of the files emitted by line 125 in startDownload of DownLoadViewController.swift.

    Though I have never see the "Did finish events for background" in on line 38 get printed. Nor do I see the "All files have been downloaded" message on line 41. I set breakpoints on line 36 where the call to urlSession.getDownLoadingTasksCount is invoked, though no break there.

    I noticed in the debug log window the message:

    +backgroundSessionConfiguration: is deprecated. Please use +backgroundSessionConfigurationWithIdentifier: instead

    I commented the first call, and use the second call instead - though still no event messages are printed. The project has the 'Background fetch" checkbox set in the target as set in the downloaded project. I noticed the project is compiled using Deployment Target 7.1 which I also changed to 8.1, recompiled and ran - though still no event messages appear.

    Thanks again

    opened by appsird 0
Releases(0.2.2)
Owner
Le Van Nghia
Software Engineer. Lover of OSS. Creator of PipeCD, Promviz, LotusLoad, Hakuba, MaterialKit... 🐳
Le Van Nghia
An Generic HTTP Request Library For Swift

GRequest An HTTP request library written in Swift. ##Basic Usage Be simple, as it should be: Request("https://api.github.com/repos/lingoer/SwiftyJSON/

Ruoyu Fu 114 Oct 18, 2022
This package is meant to make http request of an easy way inspiren in the architecture of Moya package

NetworkAgent This package is meant to make http request of an easy way inspiren in the architecture of Moya package. This package is 100% free of depe

Angel Rada 19 Sep 8, 2022
Minimalist HTTP request library via async / await

Making HTTP API requests in Swift using Foundation can be verbose and use a mix of types like URL, URLComponents and URLRequest to form a request and then handling all the encoding and decoding steps later

Nicholas Maccharoli 13 Nov 5, 2022
iONess is HTTP Request Helper for iOS platform used by HCI iOS App

iONess iONess (iOS Network Session) is HTTP Request Helper for the iOS platform used by Home Credit Indonesia iOS App. It uses Ergo as a concurrent he

OSFE Homecredit Indonesia 1 Mar 28, 2022
Deal with query items, HTTP headers, request body and more in an easy, declarative way

Reusable system for complex URL requests with Swift. Deal with query items, HTTP headers, request body and more in an easy, declarative way. Check out our engineering blog to learn more!

Parable Health 19 Sep 5, 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
Thin wrapper around NSURLSession in swift. Simplifies HTTP requests.

SwiftHTTP SwiftHTTP is a thin wrapper around NSURLSession in Swift to simplify HTTP requests. Features Convenient Closure APIs Simple Queue Support Pa

Dalton 1.9k Dec 7, 2022
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
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
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
Type-safe networking abstraction layer that associates request type with response type.

APIKit APIKit is a type-safe networking abstraction layer that associates request type with response type. // SearchRepositoriesRequest conforms to Re

Yosuke Ishikawa 1.9k Dec 30, 2022
Automatically sets the network activity indicator for any performed request.

BigBrother BIG BROTHER IS WATCHING YOU. BigBrother is a Swift library made for iOS that automatically watches for any performed request and sets the n

Marcelo Fabri 446 Dec 17, 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
YTKNetwork is a high level request util based on AFNetworking.

YTKNetwork What YTKNetwork is a high level request util based on AFNetworking. It's developed by the iOS Team of YuanTiKu. It provides a High Level AP

猿辅导技术团队 6.5k Jan 6, 2023
DBNetworkStack is a network abstraction for fetching request and mapping them to model objects

DBNetworkStack Main Features ?? Typed network resources ?? Value oriented architecture ?? Exchangeable implementations ?? Extendable API ?? Composable

DB Systel GmbH 33 Jan 10, 2022
An iOS library to route API paths to objects on client side with request, mapping, routing and auth layers

WANetworkRouting Developed and Maintained by ipodishima Founder & CTO at Wasappli Inc. Sponsored by Wisembly A routing library to fetch objects from a

null 10 Nov 20, 2022
Tiny http server engine written in Swift programming language.

What is Swifter? Tiny http server engine written in Swift programming language. Branches * stable - lands on CocoaPods and others. Supports the latest

null 3.6k Dec 31, 2022
A simple GCD based HTTP client and server, written in 'pure' Swift

SwiftyHTTP Note: I'm probably not going to update this any further - If you need a Swift networking toolset for the server side, consider: Macro.swift

Always Right Institute 116 Aug 6, 2022
A simple HTTP server written in Swift

http4swift http4swift is a tiny HTTP server library for Nest-compatible applications. This project is unstable, and the API might be changed at anytim

Shun Takebayashi 27 Jun 29, 2022