Skip to content

Instantly share code, notes, and snippets.

@Deco354
Created November 3, 2019 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deco354/cc2d30d28767a82464ac048141e25751 to your computer and use it in GitHub Desktop.
Save Deco354/cc2d30d28767a82464ac048141e25751 to your computer and use it in GitHub Desktop.
Uploads image to TinyPNG API via Swift and prints location
//
// 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