Skip to content

Commit

Permalink
added swiftlint
Browse files Browse the repository at this point in the history
  • Loading branch information
Noel Portugal committed Oct 3, 2016
1 parent af715a0 commit 062879e
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 110 deletions.
17 changes: 17 additions & 0 deletions CaptionBot.xcodeproj/project.pbxproj
Expand Up @@ -162,6 +162,7 @@
C480B47A1DA16D26002BB5D9 /* Frameworks */,
C480B47B1DA16D26002BB5D9 /* Headers */,
C480B47C1DA16D26002BB5D9 /* Resources */,
C4003A831DA22DF600F17FE2 /* ShellScript */,
);
buildRules = (
);
Expand Down Expand Up @@ -265,6 +266,22 @@
};
/* End PBXResourcesBuildPhase section */

/* Begin PBXShellScriptBuildPhase section */
C4003A831DA22DF600F17FE2 /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi";
};
/* End PBXShellScriptBuildPhase section */

/* Begin PBXSourcesBuildPhase section */
C458BD291DA18B7F00B0111A /* Sources */ = {
isa = PBXSourcesBuildPhase;
Expand Down
113 changes: 48 additions & 65 deletions CaptionBot/CaptionBot.swift
Expand Up @@ -9,135 +9,130 @@
import UIKit

public func captionBot(url: String, completion: @escaping (String?, Error?) -> Void) {

getConversationId(){ conversationId, error in
getConversationId() { conversationId, error in
if let conversationId = conversationId {
analyzeImage(conversationId: conversationId, userMessage: url){ message, error in
analyzeImage(conversationId: conversationId, userMessage: url) { message, error in
if message != nil {
getCaption(conversationId: conversationId){ caption, error in
getCaption(conversationId: conversationId) { caption, error in
if let caption = caption {
completion(caption, nil)
return
}else{
} else {
completion(nil, error)
return
}
}
}else{
} else {
completion(nil, error)
return
}
}
}else{
}
} else {
completion(nil, error)
return
}
}

}

public func captionBot(image: UIImage, completion: @escaping (String?, Error?) -> Void){
public func captionBot(image: UIImage, completion: @escaping (String?, Error?) -> Void) {

getConversationId(){ conversationId, error in
getConversationId() { conversationId, error in
if let conversationId = conversationId {
getImageUrl(conversationId: conversationId, image: image ) { imageUrl , error in
getImageUrl(conversationId: conversationId, image: image ) {
imageUrl, error in
if let imageUrl = imageUrl {
analyzeImage(conversationId: conversationId, userMessage: imageUrl){ message, error in
analyzeImage(conversationId: conversationId, userMessage: imageUrl) {
message, error in
if message != nil {
getCaption(conversationId: conversationId){ caption, error in
getCaption(conversationId: conversationId) { caption, error in
if let caption = caption {
completion(caption, nil)
return
}else{
} else {
completion(nil, error)
return
}
}
}else{
} else {
completion(nil, error)
return
}
}
}else{
} else {
completion(nil, error)
return
}
}
}else{
} else {
completion(nil, error)
return
}
}


}

private let baseUrl = "https://www.captionbot.ai/"

private func getConversationId(completion: @escaping (String?, Error?) -> Void){
private func getConversationId(completion: @escaping (String?, Error?) -> Void) {
httpGet(url: baseUrl + "api/init") { conversationId, error in
if let conversationId = conversationId?.replacingOccurrences(of: "\"", with: "") {
completion(conversationId, nil)
return
}else {
} else {
completion(nil, error)
return
}
}
}


private func getImageUrl(conversationId: String, image: UIImage, completion: @escaping (String?, Error?) -> Void){
private func getImageUrl(conversationId: String, image: UIImage,
completion: @escaping (String?, Error?) -> Void) {
httpPostImage(url: baseUrl + "api/upload", image: image) {imageUrl, error in
if let imageUrl = imageUrl?.replacingOccurrences(of: "\"", with: "") {
completion(imageUrl, nil)
return
}else {
} else {
completion(nil, error)
return
}
}
}


private func analyzeImage(conversationId: String, userMessage: String, completion: @escaping (String?, Error?) -> Void){
let jsonDic = ["conversationId": conversationId, "userMessage" : userMessage] as Dictionary<String, String>
private func analyzeImage(conversationId: String, userMessage: String,
completion: @escaping (String?, Error?) -> Void) {
let jsonDic = ["conversationId": conversationId, "userMessage" : userMessage]
as Dictionary<String, String>
httpPostJson(url: baseUrl + "api/message", jsonDict: jsonDic) { result, error in
if result != nil {
completion("Success", nil)
return
}else {
} else {
completion(nil, error)
return
}
}
}

private func getCaption(conversationId: String, completion: @escaping (String?, Error?) -> Void){
private func getCaption(conversationId: String, completion: @escaping (String?, Error?) -> Void) {
let captionUrl = baseUrl + "api/message?waterMark=&conversationId=" + conversationId
httpGet(url: captionUrl) { html, error in
if let html = html {
var jsonString = html

jsonString.remove(at: jsonString.startIndex)
jsonString.remove(at: jsonString.index(before: jsonString.endIndex))
jsonString = jsonString.replacingOccurrences(of: "\\", with: "", options: .caseInsensitive, range: nil)

jsonString = jsonString.replacingOccurrences(of: "\\", with: "",
options: .caseInsensitive, range: nil)
let jsonDict = convertStringToDictionary(text: jsonString)
let botMessages = jsonDict?["BotMessages"] as? [String]
let message = (botMessages?[1])! as String
completion(message, nil)
return

}else {
} else {
completion(nil, error)
return
}
}
}



private func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.data(using: String.Encoding.utf8) {
do {
Expand All @@ -149,16 +144,12 @@ private func convertStringToDictionary(text: String) -> [String:AnyObject]? {
return nil
}


private func httpGet(url: String, completion: @escaping (String?, NSError?) -> Void ) {

let myUrl = URL(string: url)
var request = URLRequest(url:myUrl!)
request.httpMethod = "GET"

let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in

guard error == nil else {
completion(nil, error as NSError?)
return
Expand All @@ -167,40 +158,34 @@ private func httpGet(url: String, completion: @escaping (String?, NSError?) -> V
completion(nil, nil)
return
}

let result = String(data: data, encoding: String.Encoding.utf8)
completion(result, nil)
return
}
task.resume()
}


private func httpPostImage(url: String, image: UIImage, completion: @escaping (String?, NSError?) -> Void ) {

private func httpPostImage(url: String, image: UIImage,
completion: @escaping (String?, NSError?) -> Void ) {
let myUrl = URL(string: url)
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
let imageData = UIImageJPEGRepresentation(image, 0.5)!
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

request.setValue("multipart/form-data; boundary=\(boundary)",
forHTTPHeaderField: "Content-Type")
let body = NSMutableData()
let fname = "caption.png"
let mimetype = "image/png"

body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"image1\"; filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"image1\"; filename=\" \(fname)\"\r\n".data(
using: String.Encoding.utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(imageData)
body.append("\r\n".data(using: String.Encoding.utf8)!)

body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)

request.httpBody = body as Data


let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
guard error == nil else {
Expand All @@ -211,28 +196,28 @@ private func httpPostImage(url: String, image: UIImage, completion: @escaping (S
completion(nil, nil)
return
}

let result = String(data: data, encoding: String.Encoding.utf8)
completion(result, nil)
return
}

task.resume()

}

private func httpPostJson(url: String, jsonDict: Dictionary<String, String>, completion: @escaping (String?, NSError?) -> Void ){

private func httpPostJson(url: String, jsonDict: Dictionary<String, String>,
completion: @escaping (String?, NSError?) -> Void ) {
let nsUrl = URL(string: url)
var request = URLRequest(url:nsUrl!)
request.httpMethod = "POST"

request.httpBody = try! JSONSerialization.data(withJSONObject: jsonDict, options: [])
//request.httpBody = try! JSONSerialization.data(withJSONObject: jsonDict, options: [])
do {
try request.httpBody = JSONSerialization.data(withJSONObject: jsonDict, options: [])
} catch let error as NSError {
completion(nil, error)
return
}
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in

guard error == nil else {
completion(nil, error as NSError?)
return
Expand All @@ -241,15 +226,13 @@ private func httpPostJson(url: String, jsonDict: Dictionary<String, String>, com
completion(nil, nil)
return
}

let result = String(data: data, encoding: String.Encoding.utf8)
completion(result, nil)
return
}
task.resume()
}

private func generateBoundaryString() -> String
{
private func generateBoundaryString() -> String {
return "Boundary-\(UUID().uuidString)"
}
15 changes: 2 additions & 13 deletions CaptionBotExample/AppDelegate.swift
Expand Up @@ -13,34 +13,23 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}

func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


}

24 changes: 8 additions & 16 deletions CaptionBotExample/ViewController.swift
Expand Up @@ -13,34 +13,26 @@ class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

captionBot(url: "https://www.captionbot.ai/images/6.jpg"){ caption, error in
if let caption = caption{
captionBot(url: "https://www.captionbot.ai/images/6.jpg") { caption, error in
if let caption = caption {
print("Caption: \(caption)")
}else{
} else {
print("Error: \(error)")
//Caption: I think it's a young man jumping in the air on a skateboard.
}
}

// Caption: I think it's a young man jumping in the air on a skateboard.

let image = UIImage(named: "dog")!
captionBot(image: image){ caption, error in
if let caption = caption{
captionBot(image: image) { caption, error in
if let caption = caption {
print("Caption: \(caption)")
}else{
} else {
print("Error: \(error)")
//Caption: I think it's a brown dog with its mouth open.
}
}

// Caption: I think it's a brown dog with its mouth open.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}

0 comments on commit 062879e

Please sign in to comment.