Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Alamofire support and code improvements. #1

Merged
merged 1 commit into from
Jul 1, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Example/OkLog.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -311,12 +311,14 @@
);
inputPaths = (
"${SRCROOT}/Pods/Target Support Files/Pods-OkLog_Example/Pods-OkLog_Example-frameworks.sh",
"${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework",
"${BUILT_PRODUCTS_DIR}/GzipSwift/Gzip.framework",
"${BUILT_PRODUCTS_DIR}/OkLog/OkLog.framework",
"${BUILT_PRODUCTS_DIR}/SwiftProtobuf/SwiftProtobuf.framework",
);
name = "[CP] Embed Pods Frameworks";
outputPaths = (
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Gzip.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/OkLog.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftProtobuf.framework",
Expand Down
29 changes: 18 additions & 11 deletions Example/OkLog/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import UIKit
import OkLog
import Alamofire

class ViewController: UIViewController {

Expand Down Expand Up @@ -40,7 +41,7 @@ class ViewController: UIViewController {
@IBAction private func logPost() {

let url = URL(string: "\(Constants.urlBase)\(Constants.urlPost)")!
let request = makeRequest(url: url, method: "POST", parameters: ["key": "post value"])
let request = makeRequest(url: url, method: "POST", parameters: ["id": 1, "name": "John Johnson"])

session.dataTask(with: request) { (data, response, error) in
OkLog.log(request: request, response: response, data: data)
Expand All @@ -50,23 +51,29 @@ class ViewController: UIViewController {

@IBAction private func logPut() {

let url = URL(string: "\(Constants.urlBase)\(Constants.urlPut)")!
let request = makeRequest(url: url, method: "PUT", parameters: ["key": "put value"])
let request = Alamofire.request("\(Constants.urlBase)\(Constants.urlPut)",
method: .put,
parameters: ["id": 2, "name": "James Smith"],
encoding: JSONEncoding.default,
headers: Constants.headerFields)

session.dataTask(with: request) { (data, response, error) in
OkLog.log(request: request, response: response, data: data)
}.resume()
request.responseJSON { response in
OkLog.log(response)
}

}

@IBAction private func logDelete() {

let url = URL(string: "\(Constants.urlBase)\(Constants.urlDelete)")!
let request = makeRequest(url: url, method: "DELETE", parameters: ["key": "delete value"])
let request = Alamofire.request("\(Constants.urlBase)\(Constants.urlDelete)",
method: .delete,
parameters: ["id": 3, "name": "John Appleseed"],
encoding: JSONEncoding.default,
headers: Constants.headerFields)

session.dataTask(with: request) { (data, response, error) in
OkLog.log(request: request, response: response, data: data)
}.resume()
request.responseJSON { response in
OkLog.log(response)
}

}

Expand Down
3 changes: 1 addition & 2 deletions Example/Podfile
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use_frameworks!

target 'OkLog_Example' do
pod 'OkLog', :path => '../'
pod 'OkLog/Alamofire', :path => '../'

target 'OkLog_Tests' do
inherit! :search_paths


end
end
14 changes: 10 additions & 4 deletions Example/Podfile.lock
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
PODS:
- Alamofire (4.7.2)
- GzipSwift (4.0.4)
- OkLog (0.0.1):
- OkLog/Alamofire (0.0.2):
- Alamofire
- OkLog/Core
- OkLog/Core (0.0.2):
- GzipSwift
- SwiftProtobuf
- SwiftProtobuf (1.0.3)

DEPENDENCIES:
- OkLog (from `../`)
- OkLog/Alamofire (from `../`)

SPEC REPOS:
https://github.com/cocoapods/specs.git:
- Alamofire
- GzipSwift
- SwiftProtobuf

Expand All @@ -18,10 +23,11 @@ EXTERNAL SOURCES:
:path: "../"

SPEC CHECKSUMS:
Alamofire: e4fa87002c137ba2d8d634d2c51fabcda0d5c223
GzipSwift: 1a5bc5f7827e09846b0635b5079f1224bc3b1c3a
OkLog: cccd93df9c5e63cbeb4162a3c4056c9ae6f03ffa
OkLog: a6591fbd34b42297999bf9306a81893650b4315d
SwiftProtobuf: 5ccc0e4054e37c75800e5744acb2aa80bb72b39c

PODFILE CHECKSUM: c0a8c8d19c2b6c6b8995d6f80238d4c277ed173d
PODFILE CHECKSUM: afc34687163db7b9051dfcaa7fd4ac848d4b08c1

COCOAPODS: 1.5.3
17 changes: 13 additions & 4 deletions OkLog.podspec
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'OkLog'
s.version = '0.0.1'
s.version = '0.0.2'
s.homepage = 'https://github.com/diegotl/OkLog-iOS'
s.summary = 'A network logger for iOS.'
s.swift_version = '4.1'
Expand All @@ -10,8 +10,17 @@ Pod::Spec.new do |s|
s.source = { :git => 'https://github.com/diegotl/OkLog-iOS.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/diegotrevisan90'
s.ios.deployment_target = '8.0'
s.source_files = 'OkLog/source/**/*'
s.default_subspec = "Core"

s.dependency 'SwiftProtobuf'
s.dependency 'GzipSwift'
s.subspec 'Core' do |ss|
ss.source_files = 'OkLog/source/core/**/*'
ss.dependency 'SwiftProtobuf'
ss.dependency 'GzipSwift'
end

s.subspec 'Alamofire' do |ss|
ss.source_files = 'OkLog/source/Alamofire/'
ss.dependency "OkLog/Core"
ss.dependency 'Alamofire'
end
end
20 changes: 20 additions & 0 deletions OkLog/source/alamofire/OkLog+Alamofire.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//
// Extensions.swift
// OkLog
//
// Created by Diego Trevisan Lara on 30/06/2018.
//

import Alamofire

extension OkLog {

public static func log<T>(_ response: Alamofire.DataResponse<T>) {
log(request: response.request, response: response.response, data: response.data)
}

public static func getUrl<T>(_ response: Alamofire.DataResponse<T>) -> String {
return getUrl(request: response.request, response: response.response, data: response.data)
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//
// Constants.swift
// GzipSwift
// OkLog
//
// Created by Diego Trevisan Lara on 30/06/2018.
//
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//
// Extensions.swift
// GzipSwift
// OkLog
//
// Created by Diego Trevisan Lara on 30/06/2018.
//
Expand All @@ -20,8 +20,7 @@ extension LogData {
//logData.requestContentType
requestContentLength = Int64(request.httpBody?.count ?? 0)

requestHeaders = request.allHTTPHeaderFields?.keys.compactMap({ key -> HeaderData? in
guard let value = request.allHTTPHeaderFields?[key] else { return nil }
requestHeaders = request.allHTTPHeaderFields?.map({ key, value -> HeaderData in
var headerData = HeaderData()
headerData.name = key
headerData.value = value
Expand All @@ -38,8 +37,8 @@ extension LogData {
responseBodySize = Int64(data?.count ?? 0)
responseURL = response.url?.absoluteString ?? ""

responseHeaders = response.allHeaderFields.keys.compactMap({ key -> HeaderData? in
guard let key = key as? String, let value = response.allHeaderFields[key] as? String else { return nil }
responseHeaders = response.allHeaderFields.compactMap({ key, value -> HeaderData? in
guard let key = key as? String, let value = value as? String else { return nil }
var headerData = HeaderData()
headerData.name = key
headerData.value = value
Expand Down Expand Up @@ -82,3 +81,17 @@ extension String {
}

}

extension Dictionary {

var queryString: String {
var output: String = ""
for (key, value) in self {
output += "\(key)=\(value)&"
}

output = String(output.dropLast())
return output
}

}
17 changes: 5 additions & 12 deletions OkLog/source/OkLog.swift → OkLog/source/core/OkLog.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,12 @@ public class OkLog {
let requestBody = request?.httpBody?.safeEncoded()
let responseBody = data?.safeEncoded() ?? "0"

var url = "\(Constants.urlBaseRemote)\(Constants.urlBasePath)\(Constants.urlInfoPath)\(responseBody)"

if let requestBody = requestBody {
url.append("?qb=\(requestBody)")
}

if let logDataString = logData.safeEncoded() {
let separator = requestBody == nil ? "?" : "&"
url.append("\(separator)d=\(logDataString)")
}

url.append("&s=1")
var components = [String: Any]()
components["qb"] = requestBody
components["d"] = logData.safeEncoded()
components["s"] = 1

let url = "\(Constants.urlBaseRemote)\(Constants.urlBasePath)\(Constants.urlInfoPath)\(responseBody)?\(components.queryString)"
return url
}

Expand Down
20 changes: 17 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,25 @@ OkLog for iOS is a network logger written in Swift highly inspired by [simonperc
[![Build Status](https://app.bitrise.io/app/bf1b3bd0c95a018e/status.svg?token=UmHfbCooX9k1sF99MvMWKQ&branch=master)](https://app.bitrise.io/app/bf1b3bd0c95a018e)

## What does it do?
OkLog encodes request & response data and generates an URL from where you can see all those info nicely, making it nice to debug and share network data.
OkLog encodes request & response data and generates an URL from where you can see all those info nicely, making it easy to debug and share network data. [Here's an example](http://oklog.responseecho.com/v1/r/H4sIAAAAAAAAE1WQTU_DMAyG7_yKycepS1c2KlbEoaBJCE1CQnDrJSReGmiTkGQSUO2_47Qgxs1-_bz-GoB7FaAajhlIHjlUMDSgZQPVKmvA8B4pbODetmZWO9dhQKTqETLYa8om6976fopa5BJ9kqEWAl2kjvN8TviULrZGWKmNIl19aXf1fl2wZTYTtnceQ6B8yS7-8B036sAVEo7mFyb95nEkN0TeWmNQRG0NQaKzAScxoiE_GhVbKqzOT9SnT5c6cjpIC56s-WsgfwZ3NqSV2xjdizbMekXic0C_qBU5qfTwtrNq-8F7egbQxaORztUy_Wx8GVH_H5Y467XSacWivGTFZs2KsmDlmtoffPczMlR5fjI6l9hhpCln34MRloGoAQAA?qb=H4sIAAAAAAAAE6tWykxRsjLWUcpLzE1VslLyys_IU3AsKMhJLU5NTVGqBQDWFO9RIAAAAA==&d=H4sIAAAAAAAAE4WQzUoDMRRGKVOLhqIlIGhFyEYo4vxkLFK7G9pBkUrBVtfG6SVNGpMhkxnr1qfpo_hYTgV3oqsL957vXPhQa5xO0nmKu0vn8mIYhtv5InRgLA8XoMBBd-f71iMxQe2R0Q608-fvOeAOy3MlMuaE0aEsjI67CD0WYP2E1xBuT1cTw9M1e80V3H42Hna1IWCtsc8bT_5rk4do_4eYgOZuib1-3JdHCNVrDdmWxGgFkPtMiQpkD5Eky6Ao_G3OGuUnSpk3f2RhUVsEUwVuOltC_fzkV3JqBRcaN87lMWrNwFZg8QEvtciM1SG9DgYBlR3kPQmG92hASQW8tPIMNcfMAT6dlfqCRJTclYrEER0QejWM6PAyIjf38_XG-2j80fQXeQd4P44BAAA=&s=1).

## Installation
OkLog for iOS is integrated with [CocoaPods](http://cocoapods.org). To use it in your project, add to your `Podfile`:
```ruby
pod 'OkLog'
```
or
```ruby
pod 'OkLog/Alamofire'
```

and then don't forget running:
and then don't forget to run:
```bash
$ pod install
```

## Usage
#### URLSession
In the `URLSession`'s result closure simply call
```swift
OkLog.log(request: request, response: response, data: data)
Expand All @@ -28,6 +33,15 @@ let url = OkLog.getUrl(request: request, response: response, data: data)
```
to retrieve it and do whatever you want.

To avoid replication, consider adding it inside your API Client implementation, or as a RequestAdapter for Alamofire.
#### Alamofire
If you are using Alamofire, place
```swift
OkLog.log(response)
```
or
```swift
let url = OkLog.getUrl(response)
```
in the request's completion closure

An example project is included with a few sample requests.