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

Use temporary directory for saving logs #181

26 changes: 15 additions & 11 deletions netfox/Core/NFX.swift
Original file line number Diff line number Diff line change
Expand Up @@ -208,17 +208,8 @@ open class NFX: NSObject
internal func clearOldData()
{
NFXHTTPModelManager.sharedInstance.clear()
do {
let documentsPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first!
let filePathsArray = try FileManager.default.subpathsOfDirectory(atPath: documentsPath)
for filePath in filePathsArray {
if filePath.hasPrefix("nfx") {
try FileManager.default.removeItem(atPath: (documentsPath as NSString).appendingPathComponent(filePath))
}
}

try FileManager.default.removeItem(atPath: NFXPath.SessionLog)
} catch {}
removeNFXFiles(inside: NFXPath.Documents as String)
removeNFXFiles(inside: NFXPath.TemporaryURL.path)
}

func getIgnoredURLs() -> [String]
Expand All @@ -243,6 +234,19 @@ open class NFX: NSObject
}
return self.filters
}

private func removeNFXFiles(inside directory: String) {
do {
let filePathsArray = try FileManager.default.subpathsOfDirectory(atPath: directory)
for filePath in filePathsArray {
if filePath.hasPrefix("nfx") {
try FileManager.default.removeItem(atPath: (directory as NSString).appendingPathComponent(filePath))
}
}

try FileManager.default.removeItem(atPath: (directory as NSString).appendingPathComponent(NFXPath.SessionLogFileName))
} catch {}
}

}

Expand Down
18 changes: 8 additions & 10 deletions netfox/Core/NFXHTTPModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {

func logRequest(_ request: URLRequest)
{
formattedRequestLogEntry().appendToFile(filePath: NFXPath.SessionLog)
formattedRequestLogEntry().appendToFile(at: NFXPath.SessionLogFileURL)
}

func saveErrorResponse()
Expand All @@ -99,7 +99,7 @@ fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
self.timeInterval = Float(self.responseDate!.timeIntervalSince(self.requestDate!))

saveResponseBodyData(data)
formattedResponseLogEntry().appendToFile(filePath: NFXPath.SessionLog)
formattedResponseLogEntry().appendToFile(at: NFXPath.SessionLogFileURL)
}


Expand All @@ -108,7 +108,7 @@ fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
let tempBodyString = NSString.init(data: data, encoding: String.Encoding.utf8.rawValue)
self.requestBodyLength = data.count
if (tempBodyString != nil) {
saveData(tempBodyString!, toFile: getRequestBodyFilepath())
saveData(data, toFile: getRequestBodyFilepath())
}
}

Expand All @@ -127,7 +127,7 @@ fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {

if (bodyString != nil) {
self.responseBodyLength = data.count
saveData(bodyString!, toFile: getResponseBodyFilepath())
saveData(data, toFile: getResponseBodyFilepath())
}

}
Expand Down Expand Up @@ -192,15 +192,13 @@ fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {

@objc public func getDocumentsPath() -> String
{
return NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first!
return NFXPath.TemporaryURL.path
}

@objc public func saveData(_ dataString: NSString, toFile: String)
@objc public func saveData(_ data: Data, toFile: String)
{
do {
try dataString.write(toFile: toFile, atomically: false, encoding: String.Encoding.utf8.rawValue)
} catch {
print("catch !!!")
if !FileManager.default.createFile(atPath: toFile, contents: data) {
print("NFX cannot create file: \(toFile)")
}
}

Expand Down
44 changes: 37 additions & 7 deletions netfox/Core/NFXHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -370,27 +370,30 @@ class NFXDebugInfo

struct NFXPath
{
static let Documents = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first! as NSString

static let SessionLog = NFXPath.Documents.appendingPathComponent("session.log");
static let TemporaryURL = NFX.urlForUniqueTemporaryDirectory()
@available(*, deprecated, message: "Please use TemporaryURL")
static let Documents = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.allDomainsMask, true).first! as NSString
static let SessionLogFileName = "session.log"
static var SessionLogFileURL = NFXPath.TemporaryURL.appendingPathComponent(NFXPath.SessionLogFileName)
}


extension String
{
func appendToFile(filePath: String) {
func appendToFile(at url: URL) {
let contentToAppend = self

if let fileHandle = FileHandle(forWritingAtPath: filePath) {
if let fileHandle = try? FileHandle(forWritingTo: url) {
/* Append to file */
fileHandle.seekToEndOfFile()
fileHandle.write(contentToAppend.data(using: String.Encoding.utf8)!)
} else {
/* Create new file */
do {
try contentToAppend.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
try contentToAppend.write(to: url, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Error creating \(filePath)")
print("Error creating \(url)")
}
}
}
Expand Down Expand Up @@ -480,3 +483,30 @@ public extension NSNotification.Name {
static let NFXAddedModel = Notification.Name("NFXAddedModel")
static let NFXClearedModels = Notification.Name("NFXClearedModels")
}

private extension NFX {
static func urlForUniqueTemporaryDirectory(fileManager: FileManager = .default) -> URL {
let directoryName = "nfx_directory"
let temporaryDirectory: URL
if #available(iOS 10.0, *) {
temporaryDirectory = fileManager.temporaryDirectory
} else {
temporaryDirectory = URL(string: NSTemporaryDirectory())!
}

let subDirectory = temporaryDirectory.appendingPathComponent(directoryName)

var isDirectory: ObjCBool = false
let exists = fileManager.fileExists(atPath: subDirectory.path, isDirectory: &isDirectory)

if !exists {
do {
try fileManager.createDirectory(at: subDirectory, withIntermediateDirectories: false)
} catch {
print("error")
}
}

return subDirectory
}
}
2 changes: 1 addition & 1 deletion netfox/iOS/NFXSettingsController_iOS.swift
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ class NFXSettingsController_iOS: NFXSettingsController, UITableViewDelegate, UIT
mailComposer.mailComposeDelegate = self

mailComposer.setSubject("netfox log - Session Log \(NSDate())")
if let sessionLogData = NSData(contentsOfFile: NFXPath.SessionLog as String) {
if let sessionLogData = NSData(contentsOf: NFXPath.SessionLogFileURL) {
mailComposer.addAttachmentData(sessionLogData as Data, mimeType: "text/plain", fileName: "session.log")
}

Expand Down
2 changes: 1 addition & 1 deletion netfox_ios_demo/TextViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class TextViewController: UIViewController {

guard let url = URL(string: "https://api.chucknorris.io/jokes/random") else { return }
var request = URLRequest(url: url)
request.httpBody = "TEST".data(using: .utf8)
// request.httpBody = "TEST".data(using: .utf8)
dataTask = session.dataTask(with: request) { (data, response, error) in
if let error = error {
self.handleCompletion(error: error.localizedDescription, data: data)
Expand Down