Last active
January 5, 2022 04:07
-
-
Save nazmulkp/cb864e4b77f46444c0340ea9a221b14c to your computer and use it in GitHub Desktop.
image file upload to the server Both Alamofire and URLSession
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// AppListViewController.swift | |
// TableView Custom Cell App | |
// | |
// Created by BJIT on 14/12/21. | |
// | |
import UIKit | |
import Alamofire | |
class AppListViewController: UIViewController { | |
var articals = [Artical]() | |
// MARK: - Properties | |
private var tags: [String]? | |
private var colors: [PhotoColor]? | |
var vm = VM() | |
@IBOutlet weak var appListTableView: UITableView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// getData() | |
// getData3rtParty() | |
// searchStarships(for: "wing", completion: (String) -> Void) | |
vm.searchStarships(for: "wing") { articals in | |
self.articals = articals | |
self.appListTableView.reloadData() | |
} | |
let fileName = "colorBattle.jpg" | |
let image = UIImage(named: fileName) | |
upload3rdPartyWithoutBestPractice(image: (image?.pngData())!) | |
setupTableView() | |
} | |
func setupTableView(){ | |
appListTableView.delegate = self | |
appListTableView.dataSource = self | |
appListTableView.register(AppInfoCell.nib(), forCellReuseIdentifier: AppInfoCell.identifier) | |
appListTableView.separatorStyle = .none | |
appListTableView.contentInset = UIEdgeInsets(top: 31, left: 0, bottom: 0, right: 0) | |
} | |
} | |
extension AppListViewController: UITableViewDelegate,UITableViewDataSource{ | |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return articals.count | |
} | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCell(withIdentifier: AppInfoCell.identifier, for: indexPath) as! AppInfoCell | |
cell.configureCell(appInfo: articals[indexPath.row]) | |
return cell | |
} | |
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { | |
return 70 | |
} | |
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { | |
if editingStyle == .delete{ | |
articals.remove(at: indexPath.row) | |
tableView.deleteRows(at: [indexPath], with: .automatic) | |
} | |
} | |
} | |
extension AppListViewController { | |
func upload1stParty(){ | |
let fileName = "colorBattle.jpg" | |
let image = UIImage(named: fileName) | |
let paramName = "image" | |
let url = URL(string: "https://api.imagga.com/v2/uploads") | |
// generate boundary string using a unique per-app string | |
let boundary = UUID().uuidString | |
let session = URLSession.shared | |
// Set the URLRequest to POST and to the specified URL | |
var urlRequest = URLRequest(url: url!) | |
urlRequest.httpMethod = "POST" | |
// Set Content-Type Header to multipart/form-data, this is equivalent to submitting form data with file upload in a web browser | |
// And the boundary is also set here | |
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") | |
urlRequest.setValue("Basic YWNjX2Q3N2YyODllZWJlNjk4NToxZGRjMjA0N2MwZGJiOGNhY2U1M2ZhODQzMzA1OTlmYg==", forHTTPHeaderField: "Authorization") | |
var data = Data() | |
// Add the image data to the raw http request data | |
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!) | |
data.append("Content-Disposition: form-data; name=\"\(paramName)\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!) | |
data.append("Content-Type: \"content-type header\"\r\n\r\n".data(using: .utf8)!) | |
data.append(image!.pngData()!) | |
data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!) | |
// Send a POST request to the URL, with the data we created earlier | |
session.uploadTask(with: urlRequest, from: data, completionHandler: { responseData, response, error in | |
//print(String(data: response!, encoding: .utf8)) | |
if error == nil { | |
let jsonData = try? JSONSerialization.jsonObject(with: responseData!, options: .allowFragments) | |
if let json = jsonData as? [String: Any] { | |
print(json) | |
}else{ | |
print(String(data: responseData!, encoding: .utf8)) | |
} | |
}else{ | |
print(error.debugDescription) | |
} | |
}).resume() | |
return | |
} | |
func upload3rdParty(image: Data, to url: Alamofire.URLRequestConvertible) { | |
AF.upload(multipartFormData: { multiPart in | |
multiPart.append(image, withName: "image", fileName: "file.png", mimeType: "image/png") | |
}, with: url) | |
.uploadProgress(queue: .main, closure: { progress in | |
//Current upload progress of file | |
print("Upload Progress: \(progress.fractionCompleted)") | |
}) | |
.responseJSON(completionHandler: { data in | |
//Do what ever you want to do with response | |
print(data.debugDescription) | |
}) | |
} | |
func upload3rdPartyWithoutBestPractice(image: Data) { | |
let headers: HTTPHeaders = [ | |
"Content-type": "multipart/form-data" , | |
"Authorization" :"Basic YWNjX2Q3N2YyODllZWJlNjk4NToxZGRjMjA0N2MwZGJiOGNhY2U1M2ZhODQzMzA1OTlmYg==" | |
] | |
AF.upload( | |
multipartFormData: { multipartFormData in | |
multipartFormData.append(image, withName: "image", fileName: "file.png", mimeType: "image/png") | |
}, | |
to: "https://api.imagga.com/v2/uploads", method: .post , headers: headers) | |
.response { resp in | |
print(resp.debugDescription) | |
} | |
} | |
} | |
// | |
// ImaggaRouter.swift | |
// TableView Custom Cell App | |
// | |
// Created by MacBook Air M1 on 4/1/22. | |
// | |
import Alamofire | |
public enum ImaggaRouter: URLRequestConvertible { | |
enum Constants { | |
static let baseURLPath = "https://api.imagga.com/v2" | |
static let authenticationToken = "Basic YWNjX2Q3N2YyODllZWJlNjk4NToxZGRjMjA0N2MwZGJiOGNhY2U1M2ZhODQzMzA1OTlmYg==" | |
} | |
case uploads | |
case tags(String) | |
case colors(String) | |
var method: HTTPMethod { | |
switch self { | |
case .uploads: | |
return .post | |
case .tags, .colors: | |
return .get | |
} | |
} | |
var path: String { | |
switch self { | |
case .uploads: | |
return "/uploads" | |
case .tags: | |
return "/tagging" | |
case .colors: | |
return "/colors" | |
} | |
} | |
var parameters: [String: Any] { | |
switch self { | |
case .tags(let contentID): | |
return ["content": contentID] | |
case .colors(let contentID): | |
return ["content": contentID, "extract_object_colors": 0] | |
default: | |
return [:] | |
} | |
} | |
public func asURLRequest() throws -> URLRequest { | |
let url = try Constants.baseURLPath.asURL() | |
var request = URLRequest(url: url.appendingPathComponent(path)) | |
request.httpMethod = method.rawValue | |
request.setValue(Constants.authenticationToken, forHTTPHeaderField: "Authorization") | |
request.timeoutInterval = TimeInterval(10 * 1000) | |
return try URLEncoding.default.encode(request, with: parameters) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment