Skip to content

Commit

Permalink
- Able to Read the CSV file and convert to CSV class(Object Oriented …
Browse files Browse the repository at this point in the history
…Approach).

- Refactored CSV Export class.
  • Loading branch information
vigneshuvi committed Dec 8, 2017
1 parent bc7cf4f commit 0e2528b
Show file tree
Hide file tree
Showing 7 changed files with 114 additions and 19 deletions.
20 changes: 17 additions & 3 deletions Examples/SampleSwift/SampleSwift.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -331,13 +331,16 @@
files = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-SampleSwiftTests-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n";
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
33A400582F818FDFD5E2610C /* [CP] Embed Pods Frameworks */ = {
Expand All @@ -346,9 +349,14 @@
files = (
);
inputPaths = (
"${SRCROOT}/Pods/Target Support Files/Pods-SampleSwift/Pods-SampleSwift-frameworks.sh",
"${BUILT_PRODUCTS_DIR}/SwiftCSVExport/SwiftCSVExport.framework",
"${BUILT_PRODUCTS_DIR}/SwiftLoggly/SwiftLoggly.framework",
);
name = "[CP] Embed Pods Frameworks";
outputPaths = (
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftCSVExport.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftLoggly.framework",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
Expand All @@ -361,13 +369,16 @@
files = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-SampleSwiftUITests-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n";
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
8523F8CAD25749EA216FAF6D /* [CP] Embed Pods Frameworks */ = {
Expand Down Expand Up @@ -436,13 +447,16 @@
files = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-SampleSwift-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n";
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
Expand Down
15 changes: 14 additions & 1 deletion Examples/SampleSwift/SampleSwift/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,16 @@ class ViewController: UIViewController {
data.add(user1);
data.add(user2);

let filePath:String = SwiftCSVExport.exportCSV("userlist",fields: ["name", "email", "address"],values: data);
// Create a object for write CSV
let writeCSVObj = CSV()
writeCSVObj.rows = data
writeCSVObj.fields = ["name", "email", "address"]
writeCSVObj.name = "userlist"

// Write File using CSV class object
let filePath:String = SwiftCSVExport.exportCSV(writeCSVObj);
print(filePath)


let request = NSURLRequest(url: URL(fileURLWithPath: filePath) )
webview.loadRequest(request as URLRequest)
Expand All @@ -53,6 +61,11 @@ class ViewController: UIViewController {
loggly(LogType.Info, dictionary: fileDetails)
}

// Read File in Object Oriented Way
let readCSVObj = readCSVObject(filePath);

// Use 'SwiftLoggly' pod framework to print the Dictionary
loggly(LogType.Info, text: readCSVObj.name)

}

Expand Down
48 changes: 48 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Simple way to export csv file with rich feature framework and written in Swift.
- Able to set CSV headers using fields.
- Able to convert JSON string into CSV.
- Able to Read the CSV file and convert to NSDictionary.
- Able to Read the CSV file and convert to CSV class(Object Oriented Approach).
- Support CocoaPods, mac OS and Vapor framework(Swift Package Manager).
- Able to encoding CSV based on String.Encoding Type(utf8, ascii, unicode, utf16, etc) Refer: String.Encoding.
- Able to view the exported CSV documents in iOS Files app by enabling the configuration in your project.
Expand Down Expand Up @@ -240,6 +241,53 @@ if fileDetails.allKeys.count > 0 {
}


```

### Example 7 - Swift - Object Oriented Approach

```swift

// Generate CSV file
let user1:NSMutableDictionary = NSMutableDictionary()
user1.setObject("vignesh", forKey: "name" as NSCopying);
user1.setObject("vigneshuvi@gmail.com", forKey: "email" as NSCopying);
user1.setObject("Hi Vignesh, \nhow are you? \t Shall we meet tomorrow? \r Thanks ", forKey: "address" as NSCopying);

let user2:NSMutableDictionary = NSMutableDictionary()
user2.setObject("vinoth", forKey: "name" as NSCopying);
user2.setObject("vinoth@gmail.com", forKey: "email" as NSCopying);
user2.setObject("Hi Vinoth, \nHow are you? \t Shall we meet tomorrow? \r Thanks ", forKey: "address" as NSCopying);


let data:NSMutableArray = NSMutableArray()
data.add(user1);
data.add(user2);

// Create a object for write CSV
let writeCSVObj = CSV()
writeCSVObj.rows = data
writeCSVObj.fields = ["name", "email", "address"]
writeCSVObj.name = "userlist"

// Write File using CSV class object
let filePath:String = SwiftCSVExport.exportCSV(writeCSVObj);
print(filePath)

// Read File in Object Oriented Way
let readCSVObj = readCSVObject(filePath);

// Use 'SwiftLoggly' pod framework to print the Dictionary
loggly(LogType.Info, text: readCSVObj.name)


```

### Write Output:

```swift

Output: userlist

```


Expand Down
4 changes: 2 additions & 2 deletions SwiftCSVExport.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ Pod::Spec.new do |s|
#

s.name = "SwiftCSVExport"
s.version = "1.0.5"
s.summary = "Simple way to export csv file with rich feature framework and written in Swift 3."
s.version = "1.0.6"
s.summary = "Simple way to export csv file with rich feature framework and written in Swift 3 & 4."

# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
Expand Down
4 changes: 2 additions & 2 deletions SwiftCSVExport.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,7 @@
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_SWIFT3_OBJC_INFERENCE = On;
SWIFT_SWIFT3_OBJC_INFERENCE = Default;
SWIFT_VERSION = 4.0;
};
name = Debug;
Expand All @@ -538,7 +538,7 @@
PRODUCT_BUNDLE_IDENTIFIER = vigneshuvi.SwiftCSVExport;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_SWIFT3_OBJC_INFERENCE = On;
SWIFT_SWIFT3_OBJC_INFERENCE = Default;
SWIFT_VERSION = 4.0;
};
name = Release;
Expand Down
37 changes: 26 additions & 11 deletions SwiftCSVExport/Sources/CSVExport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ public enum DividerType: String {
case semicolon = ";"
}

@objc open class CSV:NSObject {
var fields:NSArray = []
var rows:NSArray = []
var name:String = ""
var delimiter:String = DividerType.comma.rawValue
@objc public class CSV:NSObject {
open var fields:NSArray = []
open var rows:NSArray = []
open var name:String = ""
open var delimiter:String = DividerType.comma.rawValue
}

//MARK: - Extension for String to find length
Expand All @@ -30,6 +30,21 @@ extension String {
return result
}

func split(regex pattern: String) -> [String] {

guard let re = try? NSRegularExpression(pattern: pattern, options: [])
else { return [] }

let nsString = self as NSString // needed for range compatibility
let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
let modifiedString = re.stringByReplacingMatches(
in: self,
options: [],
range: NSRange(location: 0, length: nsString.length),
withTemplate: stop)
return modifiedString.components(separatedBy: stop)
}

var length: Int {
return self.count
}
Expand Down Expand Up @@ -227,9 +242,10 @@ extension String {
return rowsDictionary;
}

func splitUsingDelimiter(_ string: String, separatedBy: String) -> NSArray {
func splitUsingDelimiter(_ string: String, separatedBy: String) -> [String] {
if string.length > 0 {
return string.components(separatedBy: separatedBy) as NSArray;
let t1 = string.components(separatedBy: separatedBy) as [String];
return t1.filter{ !$0.isEmpty }
}
return [];
}
Expand Down Expand Up @@ -261,8 +277,7 @@ extension String {
if csvText.length > 0 {

// Split based on Newline delimiter
//let csvArray = self.splitUsingDelimiter(csvText, separatedBy: "\n") as NSArray
let csvArray = csvText.lines
let csvArray:[String] = self.splitUsingDelimiter(csvText, separatedBy: "\n")
if csvArray.count >= 2 {
var fieldsArray:NSArray = [];
let rowsArray:NSMutableArray = NSMutableArray()
Expand All @@ -273,9 +288,9 @@ extension String {
fieldsArray = self.splitUsingDelimiter(row, separatedBy: div) as NSArray;
} else {
// Get the CSV values
let valuesArray = self.splitUsingDelimiter(row, separatedBy: div) as NSArray;
let valuesArray = self.splitUsingDelimiter(row, separatedBy: "\"\(div)") as NSArray;
if valuesArray.count == fieldsArray.count && valuesArray.count > 0{
let rowJson:NSMutableDictionary = self.generateDict(fieldsArray, valuesArray: valuesArray)
let rowJson:NSMutableDictionary = self.generateDict(fieldsArray, valuesArray: valuesArray as NSArray)
if rowJson.allKeys.count > 0 && valuesArray.count == rowJson.allKeys.count && rowJson.allKeys.count == fieldsArray.count {
rowsArray.add(rowJson)
}
Expand Down
5 changes: 5 additions & 0 deletions SwiftCSVExportTests/SwiftCSVExportTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,15 @@ class SwiftCSVExportTests: XCTestCase {
let path:String = SwiftCSVExport.exportCSV("numberList",fields: fields,values: numberArray);
print(path)

// Read CSV as NSMutableDictionary object
let numberDetails = readCSV(path);
if numberDetails.allKeys.count > 0 {
print(numberDetails)
}

// Read CSV as CSV class object
let csvObj = readCSVObject(path);
loggly(LogType.Info, text: csvObj.name)
}

func testPerformanceExample() {
Expand Down

0 comments on commit 0e2528b

Please sign in to comment.