Skip to content

Commit

Permalink
Merge pull request #7 from thehung111/master
Browse files Browse the repository at this point in the history
DR-1342 Add ViSearch client init by app key
  • Loading branch information
thehung111 authored Jan 20, 2017
2 parents 9b774e8 + a9e31b2 commit f91b6e2
Show file tree
Hide file tree
Showing 8 changed files with 126 additions and 17 deletions.
8 changes: 6 additions & 2 deletions Example/Example/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

// TODO: fill in your access key and secret here
ViSearch.sharedInstance.setup(accessKey: "", secret: "")
// TODO: fill in your app key here
// init search client with widget key
ViSearch.sharedInstance.setup(appKey: "")

// old way of init ViSearch client
// ViSearch.sharedInstance.setup(accessKey: "", secret: "")

return true
}
Expand Down
4 changes: 2 additions & 2 deletions Example/Example/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<string>1.1</string>
<key>CFBundleVersion</key>
<string>1</string>
<string>2</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
Expand Down
19 changes: 14 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
2. [Setup](#2-setup)
- 2.1 [Run the Demo](#21-run-the-demo)
- 2.2 [Set up Xcode Project](#22-set-up-xcode-project)
- 2.3 [Import ViSearch SDK](#23-import-visearch-sdk)
- 2.3 [Import ViSearch Swift SDK](##23-import-visearch-swift-sdk)
- 2.4 [Add Privacy Usage Description](#24-add-privacy-usage-description)
3. [Initialization](#3-initialization)
4. [Solutions](#4-solutions)
Expand All @@ -36,7 +36,7 @@ ViSearch is an API that provides accurate, reliable and scalable image search. V

The ViSearch iOS SDK is an open source software to provide easy integration of ViSearch Search API with your iOS applications. It provides four search methods based on the ViSearch Solution APIs - Find Similar, You May Also Like, Search By Image and Search By Color. For source code and references, please visit the [Github Repository](https://github.com/visenze/visearch-sdk-swift).

>Current stable version: 1.0
>Current stable version: 1.1.0
>Supported iOS version: iOS 8.x and higher
Expand All @@ -49,10 +49,14 @@ The source code of a demo application is provided together with the SDK ([demo](

<img src="./doc/xcode_1_1.png" alt="screenshot" height="200">

You should change the access key and secret key in AppDelegate file to your own key pair before running.
You should initialize the ViSearch client in AppDelegate file by using your app key or access/secret key pair.

```swift

// recommended way of init ViSearch client with app key
ViSearch.sharedInstance.setup(appKey: "YOUR_APP_KEY")

// old way of init ViSearch client with access and secret key pair
ViSearch.sharedInstance.setup(accessKey: "YOUR_ACCESS_KEY", secret: "YOUR_SECRET_KEY")

```
Expand Down Expand Up @@ -94,7 +98,7 @@ platform :ios, '9.0'
use_frameworks!
target '<Your Target Name>' do
pod 'ViSearchSDK', '~>1.0'
pod 'ViSearchSDK', '~>1.1.0'
end
...
```
Expand Down Expand Up @@ -133,12 +137,17 @@ You are done!
iOS 10 now requires user permission to access camera and photo library. If your app requires these access, please add description for NSCameraUsageDescription, NSPhotoLibraryUsageDescription in the Info.plist. More details can be found [here](https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW24).

## 3. Initialization
`ViSearch` **must** be initialized with an accessKey/secretKey pair **before** it can be used.
`ViSearch` **must** be initialized with an `appKey` or `accessKey`/`secretKey` pair **before** it can be used.

```swift
import ViSearchSDK
...
// using default ViSearch client. The client, by default, will connect to Visenze's server

// recommended way of init ViSearch client with app key
ViSearch.sharedInstance.setup(appKey: "YOUR_APP_KEY")

// old way of init ViSearch client with access and secret key pair
ViSearch.sharedInstance.setup(accessKey: "YOUR_ACCESS_KEY", secret: "YOUR_SECRET_KEY")

...
Expand Down
2 changes: 1 addition & 1 deletion ViSearchSDK.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Pod::Spec.new do |s|


s.name = "ViSearchSDK"
s.version = "1.0.2"
s.version = "1.1.0"
s.summary = "A Visual Search API solution (Swift SDK)"

s.description = <<-DESC
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ open class ViRequestSerialization {
return "\(baseUrl)/\(apiEndPoint.rawValue)?\(queryString)"
}

/// generate the url with query string and escape parameter properly
public func generateRequestUrl( baseUrl: String , apiEndPoint: ViAPIEndPoints , searchParams : ViSearchParamsProtocol, appKey: String) -> String {

var searchParamsDict : [String: Any] = searchParams.toDict()
searchParamsDict["access_key"] = appKey

let queryString = generateQueryString(searchParamsDict)

return "\(baseUrl)/\(apiEndPoint.rawValue)?\(queryString)"
}

/// generate the query string to append to the url
public func generateQueryString(_ parameters: [String: Any]) -> String {
var components: [(String, String)] = []
Expand Down
16 changes: 16 additions & 0 deletions ViSearchSDK/ViSearchSDK/Classes/ViSearch.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,24 @@ open class ViSearch: NSObject {

client?.accessKey = accessKey
client?.secret = secret
client?.isAppKeyEnabled = false
}

/// Setup API client. Must be called first before various API calls
///
/// - parameter appKey: application app key
public func setup(appKey: String) -> Void {
if client == nil {
client = ViSearchClient(appKey: appKey)
}

client?.accessKey = appKey
client?.isAppKeyEnabled = true

}



// MARK: API calls

/// Search by Image API
Expand Down
81 changes: 75 additions & 6 deletions ViSearchSDK/ViSearchSDK/Classes/ViSearchClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,12 @@ open class ViSearchClient: NSObject, URLSessionDelegate {
public typealias FailureHandler = (Error) -> ()

// MARK: properties

// if isAppKeyEnabled is true, this refers to the appKey. If fail it is accessKey and meant to be used with secret
public var accessKey : String
public var secret : String

// with the new authentication, this would be optional
public var secret : String = ""
public var baseUrl : String
public var trackUrl : String

Expand All @@ -37,9 +41,12 @@ open class ViSearchClient: NSObject, URLSessionDelegate {
public var timeoutInterval : TimeInterval = 10 // how long to timeout request
public var requestSerialization: ViRequestSerialization

public var userAgent : String = "visearch-swift-sdk/1.0.2"
public var userAgent : String = "visearch-swift-sdk/1.1.0"
private static let userAgentHeader : String = "X-Requested-With"

// whether to authenticate by appkey or by access/secret key point
public var isAppKeyEnabled : Bool = true


// MARK: constructors
public init?(baseUrl: String, accessKey: String , secret: String) {
Expand All @@ -59,6 +66,7 @@ open class ViSearchClient: NSObject, URLSessionDelegate {
self.baseUrl = baseUrl
self.accessKey = accessKey
self.secret = secret
self.isAppKeyEnabled = false

self.requestSerialization = ViRequestSerialization()

Expand Down Expand Up @@ -86,21 +94,74 @@ open class ViSearchClient: NSObject, URLSessionDelegate {

}

public init?(baseUrl: String, appKey: String ) {

if baseUrl.isEmpty {
return nil;
}

if appKey.isEmpty {
return nil;
}

self.baseUrl = baseUrl
self.accessKey = appKey
self.secret = ""
self.isAppKeyEnabled = true

self.requestSerialization = ViRequestSerialization()

// config default session
sessionConfig = URLSessionConfiguration.default
sessionConfig.allowsCellularAccess = true
sessionConfig.timeoutIntervalForRequest = timeoutInterval
sessionConfig.timeoutIntervalForResource = timeoutInterval

// Configuring caching behavior for the default session
let cachesDirectoryURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
let cacheURL = cachesDirectoryURL.appendingPathComponent("viSearchCache")
let diskPath = cacheURL.path

let cache = URLCache(memoryCapacity:16384, diskCapacity: 268435456, diskPath: diskPath)
sessionConfig.urlCache = cache
sessionConfig.requestCachePolicy = .useProtocolCachePolicy

session = URLSession(configuration: sessionConfig)

self.trackUrl = ViSearchClient.VISENZE_TRACK_URL

}


public convenience init?(accessKey: String , secret: String)
{
self.init( baseUrl: ViSearchClient.VISENZE_URL , accessKey: accessKey, secret: secret)
}

public convenience init?(appKey: String)
{
self.init( baseUrl: ViSearchClient.VISENZE_URL , appKey: appKey)
}

// MARK: Visenze APIs
@discardableResult public func uploadSearch(params: ViUploadSearchParams,
successHandler: @escaping SuccessHandler,
failureHandler: @escaping FailureHandler) -> URLSessionTask
{
var url : String? = nil

if self.isAppKeyEnabled {
url = requestSerialization.generateRequestUrl(baseUrl: baseUrl, apiEndPoint: .UPLOAD_SEARCH , searchParams: params, appKey: self.accessKey)
}
else {
url = requestSerialization.generateRequestUrl(baseUrl: baseUrl, apiEndPoint: .UPLOAD_SEARCH , searchParams: params)

}

// NOTE: image must be first line before generating of url
// url box parameters depend on whether the compress image is generated
let imageData: Data? = params.generateCompressImageForUpload()
let url = requestSerialization.generateRequestUrl(baseUrl: baseUrl, apiEndPoint: .UPLOAD_SEARCH , searchParams: params)
let request = NSMutableURLRequest(url: URL(string: url)! , cachePolicy: .useProtocolCachePolicy , timeoutInterval: timeoutInterval)
let request = NSMutableURLRequest(url: URL(string: url!)! , cachePolicy: .useProtocolCachePolicy , timeoutInterval: timeoutInterval)

let boundary = ViMultipartFormData.randomBoundary()
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
Expand Down Expand Up @@ -181,8 +242,16 @@ open class ViSearchClient: NSObject, URLSessionDelegate {
failureHandler: @escaping FailureHandler
) -> URLSessionTask{

let url = requestSerialization.generateRequestUrl(baseUrl: baseUrl, apiEndPoint: apiEndPoint , searchParams: params)
let request = NSMutableURLRequest(url: URL(string: url)! , cachePolicy: .useProtocolCachePolicy , timeoutInterval: timeoutInterval)
var url : String? = nil
if self.isAppKeyEnabled {
url = requestSerialization.generateRequestUrl(baseUrl: baseUrl, apiEndPoint: apiEndPoint , searchParams: params, appKey: self.accessKey)
}
else {
url = requestSerialization.generateRequestUrl(baseUrl: baseUrl, apiEndPoint: apiEndPoint , searchParams: params)

}

let request = NSMutableURLRequest(url: URL(string: url!)! , cachePolicy: .useProtocolCachePolicy , timeoutInterval: timeoutInterval)

// make tracking call to record the action
return httpGet(request: request,
Expand Down
2 changes: 1 addition & 1 deletion ViSearchSDK/ViSearchSDK/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0.2</string>
<string>1.1.0</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
Expand Down

0 comments on commit f91b6e2

Please sign in to comment.