Created
November 3, 2019 16:14
-
-
Save Deco354/cc2d30d28767a82464ac048141e25751 to your computer and use it in GitHub Desktop.
Uploads image to TinyPNG API via Swift and prints location
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
// | |
// File.swift | |
// | |
// | |
// Created by Declan on 02/11/2019. | |
// | |
import Foundation | |
public final class Imagen { | |
private let arguments: [String] | |
private lazy var imagePath: String = { | |
guard arguments.count > 1 else { exit(1) } | |
return arguments[1] | |
}() | |
private var pipe = Pipe() | |
public init(arguments: [String] = CommandLine.arguments) { | |
self.arguments = arguments | |
} | |
public func run() throws { | |
try! imageUploadProcess.run() | |
let data = pipe.fileHandleForReading.readDataToEndOfFile() | |
if let output = String(data: data, encoding: .utf8), | |
let imageURLRange = output.range(of: #"(?<=(?:location: ))https:\/\/.*"#, options: .regularExpression) { | |
print(output[imageURLRange]) | |
} | |
} | |
} | |
private extension Imagen { | |
var imageUploadProcess: Process { | |
let curl = Process() | |
curl.executableURL = URL(fileURLWithPath: "/usr/bin/curl") | |
curl.arguments = [ | |
"https://api.tinify.com/shrink", | |
"--user", | |
"api:Q1v1rkMcjjWxmYbTt4WyPzjZRMJctXhV", | |
"--data-binary", | |
"@\(imagePath)", | |
"--dump-header", | |
"/dev/stdout" | |
] | |
curl.standardOutput = pipe | |
return curl | |
} | |
private func parseImageURLLocation() { | |
guard let uploadRequestOutput = String(pipe: pipe), | |
let imageURLRange = uploadRequestOutput.range(of: #"(?<=(?:location: ))https:\/\/.*"#, options: .regularExpression) else { | |
exit(1) | |
} | |
print(uploadRequestOutput[imageURLRange]) | |
} | |
} | |
private extension String { | |
init?(pipe: Pipe) { | |
let data = pipe.fileHandleForReading.readDataToEndOfFile() | |
self.init(data: data, encoding: .utf8) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment