测试已测试 | ✗ |
Lang语言 | SwiftSwift |
许可 | MIT |
发布上次发布 | 2018年1月 |
SwiftSwift 版本 | 3.0 |
SPM支持 SPM | ✗ |
由 Maks Tishchenko 维护。
Shram - 是一个易于使用但功能强大的通过 HTTP 请求与 RESTful 网络服务通信的框架。Shram 将帮助您用几行代码向服务器发送请求。此框架的主要优势是清晰和易用。
使用 Cocoapods,您需要在 podfile 中写入 pod 'Shram', '0.1.1’
如上所述,Shram 非常易于使用。我们来了解一下。
您可以为 ShramRequest 创建对象
var request = ShramRequest(URL: "http://www.sample.com/api/method", method: "GET")
然后您可以设置以下参数
为了发送请求,您可以使用以下方法
send(completion, failure)
适用于一般请求
download(completion, progress, failure)
适用于带进度下载请求
upload(completion, progress, failure)
适用于带进度上传请求
例如
let params = [
"someKey" : "someValue"
]
var request = ShramRequest(URL: "http://www.sample.com/api/method", method: "GET")
request.parameters = params as [String : AnyObject]?
req.send(completion: { (req, data, resp) in
}) { (req, err, resp) in
}
#另一种方式#
###方法 GET###
要发送简单的 GET 请求,您需要编写以下代码
Shram.GET("http://www.sample.com/api/method",
completion: { (request, data, response) in
},
failure: { (request, error, response) in
}
)
非常简单。但如果我们要传递一些参数或头信息呢?由于 Swift 允许为函数参数设置默认值,因此您无需寻找其他方法。完整版本的 GET 方法如下
Shram.GET("http://www.sample.com/api/method",
params: params,
headers: headers,
withParseKeys: ["firstKey", "secondKey", ...],
completion: { (request, data, response) in
},
failure: { (request, error, response) in
}
)
让我们看看参数
{
"data" : {
"name": "userName",
"age": "userAge"
}
}
要从响应中得到所需数据,您需要将 withParseKeys: ["data"]
作为参数设置到 GET 函数中。
completion: 当服务器响应成功时调用的闭包。返回
failure: 当请求失败或服务器返回错误时调用的闭包。返回
如您所见,“params”、“headers”、“withParseKeys” 是可选的,您可以不传递它们而不需要它们。
###方法 POST###
方法 POST 类似。有简写和完整版本
Shram.POST("http://www.sample.com/api/method",
contentType: contentType,
completion: { (request, data, response) in
},
failure: { (request, error, response) in
}
)
Shram.POST("http://www.sample.com/api/method",
params: params,
contentType: contentType,
headers: headers,
withParseKeys: ["firstKey", "secondKey", ...],
completion: { (request, data, response) in
},
failure: { (request, error, response) in
}
)
在此方法中,您可以看到新的参数
###PUT方法###
Shram.PUT(http://www.sample.com/api/method,
params: params,
contentType: contentType,
completion: { (request, data, response) in
},
failure: { (request, error, response) in
}
)
Shram.PUT(http://www.sample.com/api/method,
params: params,
contentType: contentType,
headers: headers,
withParseKeys: ["firstKey", "secondKey", ...],
completion: { (request, data, response) in
},
failure: {(request, error, response) in
}
)
###DELETE方法###
Shram.DELETE("http://www.sample.com/api/method",
completion: { (request, data, response) in
},
failure: { (request, error, response) in
}
)
Shram.DELETE("http://www.sample.com/api/method",
params: params,
headers: headers,
withParseKeys: ["firstKey", "secondKey", ...],
completion: { (request, data, response) in
},
failure: { (request, error, response) in
}
)