I am putting together a program that reads the sensors within a cell phone and saves the sensor data to a core-data SQLite model, with each set of readings pertaining to a particular session
The program provides the user with the option to email a .csv file of a particular session.
Having never done this before, I approached the issue by initializing a delegate and context, and searching the core data for entities that pertain to a specified session. The entities that satisfy the session attribute then have their data fields (gps, mag, accel, gyro) read and put into a string. Then the string is appended to an array. All done in swift.
After the entities are searched and the array is created, I attempt to create a csv file for attachment to an email. The file is attached successfully, but my encoding technique is presenting additional data prepended and appended to the file.
I want to save a file on the phone and email a copy to the user.
Here is what I have to change the Array to NSArray before converting again to NSData:
let paths: NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true);
let path = paths[0].stringByAppendingPathComponent("SessionData.csv")
if !NSFileManager.defaultManager().fileExistsAtPath(path)
{
NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil)
}
else
{
NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil)
}
var handle: NSFileHandle = NSFileHandle(forWritingAtPath: path)
handle.truncateFileAtOffset(handle.seekToEndOfFile())
var arrayToWriteNS = (arrayToWrite as NSArray)
var dataNS: NSData = NSKeyedArchiver.archivedDataWithRootObject(arrayToWrite as NSArray)
handle.writeData(dataNS)
mc.setSubject(emailTitle)
mc.addAttachmentData(dataNS, mimeType: "text/csv", fileName: "SessionData.csv")
Here is the prepended and appended data:
bplist00‘()T$topX$objectsX$versionY$archiver—TrootĨ
!U$null“
V$classZNS.objectsÄ©ÄÄÄÄÄÄÄÄ Ä
"My Data"
“"#$'X$classesZ$classname¢%&WNSArrayXNSObjectWNSArray܆_NSKeyedArchiver(25:<IOT[fhrtvxz|~ÄÇÑ·Ø}KÁµÉQV_jmu~Üã*ù
In a large data session with 28,000 entities there may be ~750 lines of prepended data.
Any help that you can provide would be appreciated.
I'm new to iOS, Obj-C, and swift, thus I'm positive there is a better way to do this, I just haven't discovered a better method yet.
Thank you.
UPDATE: Ended up just using the NSString data encoding and writing to my file in increments:
handle.truncateFileAtOffset(handle.seekToEndOfFile())
var stringToWriteNS = (stringToWrite as NSString).dataUsingEncoding(NSUTF8StringEncoding)
handle.writeData(stringToWriteNS!)
You do not want NSKeyedArchiver, it is for archiving and restoring classes.
You need to go through the array and create a text representation of each item in a format you what to present to the user.
A quick search of CocoaPods reveals several projects that may fit you needs to generate csv format data.
This one might be what you need.
csv is fairly simple so it would be reasonable to format your data to csv by writing your own code.
Related
I am learning how to write JSON format data to an iPhone. So with one button clicked, I want to save those data to the iPhone. I looked a simple look on how to write some simple text and saved it to the iPhone file and it worked. However, I tried to apply the same idea to JSON data but still haven't figure out. I tried:
Rather than having contents equal to some written text, I tried to put it as my data (jsondata).
But it does not seem working with
try jsondata.write(to: fileURL, atomically: false, encoding: .utf8)
#IBAction func writeFiles(_ sender: Any) {
let file = "\(UUID().uuidString).txt"
let contents = "Testing"
let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = dir.appendingPathComponent(file)
do {
try contents.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {
print("Error: \(error)")
}
}
Sorry I am a bit new and learning Swift at the moment
Thanks!
Here is a simple project for you to clone or browse the source files
https://github.com/eSpecialized/WriteJsonToFiles
The View Controller contains the example;
https://github.com/eSpecialized/WriteJsonToFiles/blob/master/WriteToFiles/ViewController.swift
Basically you need to do a few steps for writing;
Assemble your objects (Strings etc).
Convert to JSONEncoded Data using the JSONEncoder.
The actual 'Data' Object can write it's binary content to storage.
To read the data;
You need a JSONDecoder.
You need the FileContents in memory using Data(contents:...)
Decode the in-memory data back into the object like it was stored.
A more complicated example of reading and writing JSON to a Web Service API is on Medium here > https://medium.com/better-programming/json-parsing-in-swift-2498099b78f
The concepts are the same, the destination changes from a file in the users document folder to a web service API. I feel that it is adequate to get you started with reading and writing JSON.
The Medium article goes a step further with introducing you to Data Models and reading and writing those Data Model Structs using the Codable protocol.
Enjoy! :)
I'm currently trying to save a jpeg representation of a UIImage with additional custom metadata (e.g. Thermal temperature statistics etc.). These don't fit within the apple predefined keys (https://developer.apple.com/documentation/imageio/cgimageproperties), so solutions I've found don't apply to my scenario.
I've tried saving the metadata with the image as a dictionary of keys and values, but the image is saved without the additional metadata.
func saveImage(imageToSave: UIImage, metadata: NSMutableDictionary) {
if let data: Data = imageToSave.jpegData(compressionQuality: ThermalImageView.JPEG_COMPRESSION) {
let fileName = self.buildFileName();
let source = CGImageSourceCreateWithData(data as CFData, nil)!;
let uniformTypeIdentifier = CGImageSourceGetType(source)!;
let destination = CGImageDestinationCreateWithURL(fileName as CFURL, uniformTypeIdentifier, 1, nil)!;
CGImageDestinationAddImageFromSource(destination, source, 0, metadata);
CGImageDestinationFinalize(destination);
}
}
When I try to read these values back with ExifTool (exiftool -j filename.jpg), the metadata is nowhere to be found. I expected this to happen as Apple seems to restrict what keys you can add to your metadata. So, is there a way to do this or should I go another route?
Thanks!
Edit: I think I may be barking up the wrong tree here. It seems like what I actually want to do is modify the header with additional metadata.
Photos framework is a way to go when dealing with metadata of assets. Moreover, PHAsset is the object you'd like to tinker with. https://developer.apple.com/documentation/photokit/phasset
One related question is: https://forums.developer.apple.com/thread/60664
If you still want to have it in your current way, perhaps try this? https://github.com/Nikita2k/SimpleExif
I am working on developing a civic engagement app that provides information on bills making their way through a particular state house. The API I am using updates every hour, if a user accesses the information within that hour, I would like to archive the most recent JSON data on their phone (and update it on the hour as well). What is the best solution for storing JSON data? Core Data, NSCoding, or UserDefaults
Core Data will be the best option to cache your data locally. UserDefaults is least recommendable as if any particular value, corresponding to the key you are trying to save, comes Nil, Your application will crash.
The most simple way is to save Serialization data as plist file:
let plistData = try PropertyListSerialization.data(fromPropertyList: jsonDict, format: .xml, options: PropertyListSerialization.WriteOptions(0))
try plistData.write(to: urlToLocalFile, options: .atomic)
And then read this file:
if let dictionary = NSDictionary(contentsOf: urlToLocalFile) {
//do something with dictionary
}
I am trying to read data from my API. I am not using JSON data because the API doesn't return an array, just a line of text. Anyways, I am using the following code to read the text from the API.
func contactVetApi(url:String){
let nsUrl = NSURL(string:url)
let task = NSURLSession.sharedSession().dataTaskWithURL(nsUrl!){
(data, response, error) in
print(data)
}
task.resume()
}
I am calling this function in the ViewDidLoad function of my ViewController file. As you can see, it takes a parameter that is a string. The parameter is the URL to read. It then translates the string into a NSUrl so it can be used with the sharedSession. I then initialize the shared session and create a data task with that url. I then print out the data it returns. The only issue is that the output isn't what I am expecting. What I am expecting is for it to say, "Future home of something quite cool." Although, this is what I am getting.
Optional(<46757475 72652068 6f6d6520 6f662073 6f6d6574 68696e67 20717569 74652063 6f6f6c>)
Optional(<46757475 72652068 6f6d6520 6f662073 6f6d6574 68696e67 20717569 74652063 6f6f6c>)
I need help figuring out why it is printing that out instead of what I am expecting. In case it is needed, the api url is http://apis.wilsonfamily5.org/vet/about.php. Before anybody asks though, I did add into the info.plist file the disabling of the iOS 9 app transport security. If you need any extra information to help me solve this problem, I would be more then happy to give it to you. I want to thank you in advance.
You currently are printing a NSData object, which will always look like that jibberish. What you actually want however is to convert the NSData to a NSString or String to create a human readable form:
var dataAsString = NSString(data: data, encoding: NSUTF8StringEncoding)
Taken from this answer.
I want to implement a web service to recover an array of my entity PictureCaptures :
PictureCaptures
---------------
- description : string
- captureDate : DateTime
- photoBinary : byte[]
The web service will be mainly called by an iOS application.
What's the best way to implement it, because of the byte array attribute?
Am I suppose to return the byte array without any transformation, as a simple JSON attribute? If yes, how to interpet the JSON response ? -In this case JSONObjectWithData:options:error: doesn't work, too much data and memory issue)-
Thank you for your help.
I would suggest you add two resources: one for the meta data (description, captureDate and so on) and one for the binary data. Let the meta data resource contain a link to the binary photo data.
Like this:
GET /images/1234
Response:
{
description: "Nice photo",
captureDate: "2012-04-23T18:25:43.511Z",
photoData: "http://example.org/images/1234/photo"
}
and http://example.org/images/1234/photo returns the raw photo data
(see also See also The "right" JSON date format for a discussion on date formats).
when you get JSON responce you shoud convert the btye array to NSData.
first add Base64.h and m file to the project ( you can find it easily on internet)
then import Base64.h
from your JSON data
NSString *data= [yourJSONDict objectForKey:#"photoBinary"];
NSData* imageData = [data base64DecodedData];
UIImage *imag=[UIImage imageWithData:imageData];
[yourImageView setImage:imag];
this might help you.