nghialv/Net

语言: Swift

git: https://github.com/nghialv/Net

用Swift编写的Http Request包装器
Http Request wrapper written in Swift
README.md (中文)

Net是一个用Swift编写的HttpRequest包装器

特征

  • GET,POST,PUT,DELETE方法
  • 强大的请求参数:嵌套参数,数字,字符串,dic,数组,图像,数据
  • Json,Image,Xml Response
  • 下载文件:resume,suspend,cancel
  • 上传文件,数据,参数(多部分)
  • 进度关闭
  • 后台下载,上传
  • 认证
  • 一批操作
  • 的baseUrl
  • 可自定义的标题

但也p

screenshot

用法

使用以下方法之一创建Net实例

// without baseURL
let net = Net()

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

HttpRequest的

获取请求
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")
    })

您也可以使用嵌套参数

// 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")]

通过在sucessHandler闭包中使用responseData,您可以快速完成  得到json字典  得到图像 *解析xml

用于GET,POST,PUT,DELETE请求。

// 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请求

Net将自动检查您的参数以发送请求作为URL编码请求或多部分请求。因此,您可以轻松发布数字,字符串,图像或二进制数据。

  • URL编码请求
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")
    })
  • 多部分请求
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请求
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")
    })
删除请求
let url = "delete_path"
let params = ["id": 10]

net.DELETE(url, params: params, successHandler: { responseData in
        NSLog("result: \(result)")
    }, failureHandler: { error in
        NSLog("Error")
    })

任务

在使用下载/上传功能之前,您必须调用setupSession方法来设置会话。

// setup session without backgroundIdentifier
net.setupSession()

要执行后台下载或上载,您必须使用后台标识符字符串调用setupSession方法。然后,即使应用程序被暂停,退出或崩溃,您的下载/上传任务也可以运行。

// 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!")
        }
    }
}
下载
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()
上传
  • 上传文件路径
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")
        }
    })
  • 上传数据
let yourData = NSData(...)

net.upload(absoluteUrl: url, data: yourData, progressHandler: { progress in
        NSLog("progress: \(progress)")
    }, completionHandler: { error in
        NSLog("Upload completed")
    })
  • 上传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")
    })

默认情况下,上载任务将以POST方式执行

  • Content-Type = application / octet-stream(上传包含文件或数据)
  • Content-Type = multipart / form-data(使用params上传)

但您可以在恢复之前配置上载任务。

// set method
yourUploadTask.setHttpMethod(.PUT)

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

积分

只需将Net文件夹拖到项目树中即可

本文使用googletrans自动翻译,仅供参考, 原文来自github.com

en_README.md

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