1.URLSession 的介绍
URLSession在2013年随着iOS7的发布一起面世,替换了原来的NSURLConnection,URLSession用于管理网络接口的创建、维护、删除等等工作.
2. URLSession的子类介绍
- URLSessionDataTask:用于简单的数据请求.
- URLSessionUploadTask:用于上传数据.
- URLSessionDownloadTask:用于下载数据.
- URLSessionStreamTask:提供TCP/IP的链接入口,可以用于双向会话.
3.通过URLSession实现上传图片
创建请求:
var r = URLRequest(url: URL(string: "https://*******")!)
r.httpMethod = "POST"
let boundary = "Boundary-\(UUID().uuidString)"
r.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
r.httpBody = createBody(parameters: [:],
boundary: boundary,
data: image.jpegData(compressionQuality:0.7)!,
mimeType: "image/JPG",
filename: "hello.JPG")
上述代码中用到的creatBody方法如下:
func createBody(parameters: [String: String],
boundary: String,
data: Data,
mimeType: String,
filename: String) -> Data {
let body = NSMutableData()
let boundaryPrefix = "--\(boundary)\r\n"
for (key, value) in parameters {
body.appendString(boundaryPrefix)
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
body.appendString(boundaryPrefix)
body.appendString("Content-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimeType)\r\n\r\n")
body.append(data)
body.appendString("\r\n")
body.appendString("--".appending(boundary.appending("--")))
return body as Data
}
对NSMutableData方法扩展:
func appendString(_ string: String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
append(data!)
}
通过URLSession上传图片:
let session = URLSession.shared.dataTask(with:r) { (data,response, error) in
if(error != nil) {
print("Error: \(error)")
}else
{
let outputStr = String(data: data!, encoding: String.Encoding.utf8) as String?
print(outputStr)
//send this block to required place
// completionBlock(outputStr!);
}
}
session.resume()
网友评论