1、URLSession请求数据
func requestData(_ url: String , _ completionHandler: @escaping (_ result: NSDictionary) -> Void) {
let url = URL(string: url)!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue(myUserAgent, forHTTPHeaderField: "User-Agent")
UIApplication.shared.isNetworkActivityIndicatorVisible = true
URLSession.shared.dataTask(with: request) { data, response, error in
if error == nil && data != nil {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
do {
completionHandler(try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary)
} catch {
print(#function)
}
return
}
}.resume()
}
使用方法:
requestData(url) { (dic) in
DispatchQueue.main.async(execute: {
print(dic)
})
}
2、URLSession加载网络图片
func downloadImageToImageDictionary(_ imageFileName: String ,_ imageView: UIImageView,_ url: String)
{
if let myImageInDictionary = myImageDictionary[imageFileName]{
DispatchQueue.main.async() { () -> Void in
imageView.image = myImageInDictionary
}
} else {
URLSession.shared.dataTask(with: URL(string: url)!) { (data, response, error) in
guard let data = data, error == nil else { return }
DispatchQueue.main.async() { () -> Void in
imageView.image = UIImage(data: data)
if UIImage(data: data) != nil {
myImageDictionary.updateValue(UIImage(data: data)!, forKey: imageFileName)
}
}
}.resume()
}
}
使用方法:
downloadImageToImageDictionary(imagePath, imageView, imagePath)
3、URLSession上传图片
public func imageUploading(fileName:String, image:UIImage,_ completion:((NSDictionary?) -> Void)!) {
let urlString = ""
let url = URL(string: urlString)!
var request:URLRequest = URLRequest(url: url, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 20)
var builder = myMultipartDataBuilder()
builder.appendFormData("filedata",content: UIImageJPEGRepresentation(image, 1.0)!,fileName: filename, contentType: "image/jpeg")
request.setMultipartBody(builder.build()!, boundary: builder.boundary)
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
if error != nil {
completion(nil)
return
}
do {
completion(try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary)
} catch {
print("POST Error:")
completion(nil)
}
})
task.resume()
}
转换成data格式
private let MultipartFormCRLF = "\r\n"
private let MutlipartFormCRLFData = MultipartFormCRLF.data(using: String.Encoding.utf8)!
public extension URLRequest {
public mutating func setMultipartBody(_ data: Data, boundary: String) {
self.httpMethod = "POST"
self.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
self.httpBody = data
self.setValue(String( data.count ), forHTTPHeaderField: "Content-Length")
self.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
self.setValue(myUserAgent, forHTTPHeaderField: "User-Agent")
}
}
extension CharacterSet {
static func MIMECharacterSet() -> CharacterSet {
let characterSet = CharacterSet(charactersIn: "\"\n\r")
return characterSet.inverted
}
}
public struct myMultipartDataBuilder {
var fields: [Data] = []
public let boundary: String
public init() {
self.boundary = NSUUID().uuidString //"0xKhTmXbhgOuNdArY000" //NSUUID().uuidString
}
public func build() -> Data? {
let data = NSMutableData()
for field in self.fields {
data.append(self.toData("--\(self.boundary)"))
data.append(MutlipartFormCRLFData)
data.append(field)
}
data.append(self.toData("--\(self.boundary)--"))
data.append(MutlipartFormCRLFData)
return (data.copy() as! Data)
}
mutating public func appendFormData(_ key: String, value: String) {
let content = "Content-Disposition: form-data; name=\"\(encode(key))\""
let data = self.merge([
self.toData(content),
MutlipartFormCRLFData,
MutlipartFormCRLFData,
self.toData(value),
MutlipartFormCRLFData
])
self.fields.append(data)
}
mutating public func appendFormData(_ name: String, content: Data, fileName: String, contentType: String) {
let contentDisposition = "Content-Disposition: form-data; name=\"\(self.encode(name))\"; filename=\"\(self.encode(fileName))\""
let contentTypeHeader = "Content-Type: \(contentType)"
let data = self.merge([
self.toData(contentDisposition),
MutlipartFormCRLFData,
self.toData(contentTypeHeader),
MutlipartFormCRLFData,
MutlipartFormCRLFData,
content,
MutlipartFormCRLFData
])
self.fields.append(data)
}
fileprivate func encode(_ string: String) -> String {
let characterSet = CharacterSet.MIMECharacterSet()
return string.addingPercentEncoding(withAllowedCharacters: characterSet)!
}
fileprivate func toData(_ string: String) -> Data {
return string.data(using: String.Encoding.utf8)!
}
fileprivate func merge(_ chunks: [Data]) -> Data {
let data = NSMutableData()
for chunk in chunks {
data.append(chunk)
}
return data.copy() as! Data
}
}