Accelerometer & Gyroscope
Category: Swift
Shake
Shake
WOEID
WOEID PLIST CSV XML JSON
WOEID
//
// WOEID.swift
// WOEID
//
// Created by Park on 11/21/15.
// Copyright © 2015 Park. All rights reserved.
//
import Foundation
class WOEID {
var code: Int64 = 0
var city: String = “”
var country: String = “”
var latitude: Double = 0.0
var longitude: Double = 0.0
init() {
}
init(code: Int64, city: String, country: String, latitude: Double, longitude: Double) {
self.code = code
self.city = city
self.country = country
self.latitude = latitude
self.longitude = longitude
}
var description : String {
get {
return “\(code),\(city),\(country),\(latitude),\(longitude)”
}
}
var xmlFormat : String {
get {
/*
let root = NSXMLElement(name: “WOEID”)
let xml = NSXMLDocument(rootElement: root)
root.addChile(NSXMLElement(name: “Code”, stringValue: “\(code)”))
root.addChile(NSXMLElement(name: “City”, stringValue: “\(city)”))
root.addChile(NSXMLElement(name: “Country”, stringValue: “\(country)”))
root.addChile(NSXMLElement(name: “Latitude”, stringValue: “\(latitude)”))
root.addChile(NSXMLElement(name: “Longitude”, stringValue: “\(longitude)”))
return xml.XMLString
*/
var xmlString = “<WOEID>\n”
xmlString += “<Code>\(self.code)</Code>\n”
xmlString += “<City>\(self.city)</City>\n”
xmlString += “<Country>\(self.country)</Country>\n”
xmlString += “<Latitude>\(self.latitude)</Latitude>\n”
xmlString += “<Longitude>\(self.longitude)</Longitude>\n”
xmlString += “</WOEID>\n”
return xmlString
}
}
}
SimpleViewController
//
// SimpleTableViewController.swift
// WOEID
//
// Created by Park on 11/22/15.
// Copyright © 2015 Park. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class SimpleViewController: UIViewController/*, MKMapViewDelegate, CLLocationManagerDelegate*/ {
var woeid: WOEID!
@IBOutlet weak var aMapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(woeid.description)
self.title = woeid.description
let center = CLLocationCoordinate2D(latitude: woeid.latitude, longitude: woeid.longitude)
let span = MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)
let region = MKCoordinateRegion(center: center, span: span)
self.aMapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = center
annotation.title = woeid.city
annotation.subtitle = woeid.country
self.aMapView.addAnnotation(annotation)
/*
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// location delegate
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
self.aMapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print(“Error: ” + error.localizedDescription)
}
/*
// MARK: – Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
WOEIDImporter
//
// WOEIDImporter.swift
// WOEID
//
// Created by Park on 11/21/15.
// Copyright © 2015 Park. All rights reserved.
//
import Foundation
extension String {
func toDouble() -> Double {
if let unwrappedNum = Double(self) {
return unwrappedNum
}
else {
print(“Error converting \”” + self + “\” to Double”)
return 0.0
}
}
func toInt64() -> Int64 {
if let unwrappedNum = Int64(self) {
return unwrappedNum
}
else {
print(“Error converting \”” + self + “\” to Int64″)
return 0
}
}
}
class WOEIDImporter: NSObject, NSXMLParserDelegate {
var woeidList : [WOEID] = [WOEID]() // XML parser woeidList
var woeid: WOEID! = nil // XML parser woeid
var parser: NSXMLParser? = nil // XML parser
var xmlData: String = “” // XML elementName data
override init() {
super.init()
print(“WOEIDImporter”)
}
func loadData() -> [WOEID] {
var woeidList:[WOEID] = [WOEID] ()
woeidList.append(WOEID(code: 4118, city: “Toronto”, country: “Canada”, latitude: 43.64856, longitude: -79.385368))
woeidList.append(WOEID(code: 44418, city: “London”, country: “United Kingdom”, latitude: 51.507702, longitude: -0.12797))
woeidList.append(WOEID(code: 2487956, city: “San Francisco”, country: “United States”, latitude: 37.747398, longitude: -122.439217))
woeidList.append(WOEID(code: 1132599, city: “Seoul”, country: “South Korea”, latitude: 37.557121, longitude: 126.977379))
woeidList.append(WOEID(code: 718345, city: “Milan”, country: “Italy”, latitude: 45.4781, longitude: 9.17789))
return woeidList
}
func loadDataFromPList(path: String) -> [WOEID] {
var woeidList = [WOEID]()
let plistPath = NSBundle.mainBundle().pathForResource(path, ofType: “plist”) // load a local plist file
if plistPath != nil {
print(“loadDataToPList \(path)”)
let array = NSArray(contentsOfFile: plistPath!)
let values = array as! [AnyObject]
for item in values {
let code : Int64 = (item[0] as! NSNumber).longLongValue
let city : String = item[1] as! String
let country : String = item[2] as! String
let lat : Double = item[3] as! Double
let lon : Double = item[4] as! Double
//print(“\(code),\(city),\(country),\(lat),\(lon)”)
woeidList.append(WOEID(code: code, city: city, country: country, latitude: lat, longitude: lon))
}
}
return woeidList
}
func exportDataToPList(data: [WOEID], path: String) {
print(“exportDataToPList \(path)”)
let fileManager = NSFileManager.defaultManager()
let dirs = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
let dir = dirs[0] // documents directory
let plistPath = dir + “/” + path + “.plist”
if !fileManager.fileExistsAtPath(plistPath) {
let array = NSMutableArray()
for item in data {
let itemArray = NSMutableArray()
itemArray[0] = NSNumber(longLong: item.code)
itemArray[1] = item.city
itemArray[2] = item.country
itemArray[3] = NSNumber(double: item.latitude)
itemArray[4] = NSNumber(double: item.longitude)
array.addObject(itemArray)
}
print(array)
let result : Bool = array.writeToFile(plistPath, atomically: true)
if result == true {
print(“File \(plistPath) file created”)
}
}
}
func loadDataFromCSV(path: String) -> [WOEID] {
var woeidList:[WOEID] = [WOEID] ()
let csvPath = NSBundle.mainBundle().pathForResource(path, ofType: “csv”) // load a local csv file
if csvPath != nil {
let data = NSData(contentsOfFile: csvPath!)
if let content = String(data: data!, encoding: NSUTF8StringEncoding) {
// cleaning “\r” “\n\n” string first
let newline = NSCharacterSet.newlineCharacterSet()
let delimiter = NSCharacterSet(charactersInString: “,”)
var contentToParse = content.stringByReplacingOccurrencesOfString(“\r”, withString: “\n”)
contentToParse = contentToParse.stringByReplacingOccurrencesOfString(“\n\n”, withString: “\n”)
// get list of eachline
let lines:[String] = contentToParse.componentsSeparatedByCharactersInSet(newline) as [String]
// list of deliminated strings for each line
for line in lines {
let values: [String] = line.componentsSeparatedByCharactersInSet(delimiter)
if values != [“”] {
//print(values)
woeidList.append(WOEID(code: values[0].toInt64(), city: values[1], country: values[2], latitude: values[3].toDouble(), longitude: values[4].toDouble()))
}
}
}
}
return woeidList
}
func exportDataToCSV(data: [WOEID], path: String) {
print(“exportDataToCSV \(path)”)
var contentsOfFile: String = “”
for item in data {
//print(item.description)
contentsOfFile.appendContentsOf(item.description + “\n”)
}
//print(contentsOfFile)
let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as [String]
let dir = dirs[0]
let csvPath = dir + “/” + path + “.csv”
do {
try contentsOfFile.writeToFile(csvPath, atomically: true, encoding: NSUTF8StringEncoding)
print(“File \(csvPath) file created”)
} catch {
print(“Fail to create \(csvPath) file”)
}
}
func loadDataFromJSON(path: String) -> [WOEID] {
var woeidList = [WOEID]()
let jsonPath = NSBundle.mainBundle().pathForResource(path, ofType: “json”) // load a local json file
if jsonPath != nil {
print(“loadDataFromJSON \(path)”)
let data = NSData(contentsOfFile: jsonPath!)
//let error: NSError?
do {
if let decodedJson = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? [AnyObject] {
for item in decodedJson {
//print(item)
let code : Int64 = (item[“Code”] as! NSNumber).longLongValue
let city : String = item[“City”] as! String
let country : String = item[“Country”] as! String
let lat : Double = item[“Latitude”] as! Double
let lon : Double = item[“Longitude”] as! Double
//print(“\(code),\(city),\(country),\(lat),\(lon)”)
woeidList.append(WOEID(code: code, city: city, country: country, latitude: lat, longitude: lon))
}
}
}
catch {
print(error)
}
}
return woeidList
}
func exportDataToJSON(data: [WOEID], path: String) {
print(“exportDataToJSON \(path)”)
let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as [String]
let dir = dirs[0]
let jsonPath = dir + “/” + path + “.json”
let array = NSMutableArray()
for item in data {
let itemData = NSMutableDictionary()
itemData.addEntriesFromDictionary([“Code” : NSNumber(longLong: item.code)])
itemData.addEntriesFromDictionary([“City” : NSString(string: item.city)])
itemData.addEntriesFromDictionary([“Country” : NSString(string: item.country)])
itemData.addEntriesFromDictionary([“Latitude” : NSNumber(double: item.latitude)])
itemData.addEntriesFromDictionary([“Longitude” : NSNumber(double: item.longitude)])
array.addObject(itemData)
}
//print(array)
if let outputJson = NSOutputStream(toFileAtPath: jsonPath, append: false) {
outputJson.open()
var error: NSError?
NSJSONSerialization.writeJSONObject(array, toStream: outputJson, options: NSJSONWritingOptions.PrettyPrinted, error: &error)
outputJson.close()
}
}
func exportDataToXML(data: [WOEID], path: String) {
print(“exportDataToXML \(path)”)
// using TBXML or KissXML to write XML for better implementation
var contentsOfFile: String = “<ArrayOfWOEID>\n”
for item in data {
contentsOfFile.appendContentsOf(item.xmlFormat)
}
contentsOfFile += “</ArrayOfWOEID>”
print(contentsOfFile)
let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as [String]
let dir = dirs[0]
let xmlPath = dir + “/” + path + “.xml”
do {
try contentsOfFile.writeToFile(xmlPath, atomically: true, encoding: NSUTF8StringEncoding)
print(“File \(xmlPath) file created”)
} catch {
print(“Fail to create \(xmlPath) file”)
}
}
func loadDataFromXML(path: String) {
//parser = NSXMLParser(contentsOfURL:(NSURL(string:path))!)! // fromURL
let xmlPath = NSBundle.mainBundle().pathForResource(path, ofType: “xml”)
if xmlPath != nil {
parser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: xmlPath!))
}
if parser != nil {
parser!.delegate = self
parser!.parse()
}
}
// it calls when it finds new element
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
{
xmlData = elementName
if elementName == “WOEID” {
woeid = WOEID()
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
{
xmlData = “” // reset
if elementName == “WOEID” {
//print(woeid.description)
woeidList.append(woeid)
//woeid = nil // delete
}
}
// after find new character, it calls below
func parser(parser: NSXMLParser, foundCharacters string: String)
{
if woeid != nil {
if xmlData == “Code” {
//print(“Code” + string)
woeid.code = string.toInt64()
} else if xmlData == “City” {
//print(“City” + string)
woeid.city = string
} else if xmlData == “Country” {
//print(“Country” + string)
woeid.country = string
} else if xmlData == “Latitude” {
//print(“Latitude” + string)
woeid.latitude = string.toDouble()
} else if xmlData == “Longitude” {
//print(“Longitude” + string)
woeid.longitude = string.toDouble()
}
}
}
func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
NSLog(“failure error: %@”, parseError)
}
}
ViewController
//
// ViewController.swift
// WOEID
//
// Created by Park on 11/21/15.
// Copyright © 2015 Park. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var aTableView: UITableView!
let importer: WOEIDImporter = WOEIDImporter()
var woeidList: [WOEID]! = nil
var woeid: WOEID! = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = “WOEID”
//woeidList = importer.loadDataFromCSV(“WOEIDList”)
importer.loadDataFromXML(“WOEIDList”)
woeidList = importer.woeidList
aTableView.delegate = self
aTableView.dataSource = self
aTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: “cell”)
let tempList = importer.loadData() // test data
importer.exportDataToCSV(tempList, path: “temp”)
importer.exportDataToPList(tempList, path: “temp”)
importer.exportDataToJSON(tempList, path: “temp”)
importer.exportDataToXML(tempList, path: “temp”)
//importer.loadDataFromJSON(“WOEIDJSON”)
/*let tempList2 :[WOEID] = importer.loadDataFromPList(“WOEIDPropertyList”)
for e in tempList2 {
print(e.description)
}*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return woeidList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: UITableViewCell = aTableView.dequeueReusableCellWithIdentifier(“cell”) as UITableViewCell!
let woeid = woeidList[indexPath.row] as WOEID
cell.textLabel?.text = “\(woeid.code) \(woeid.city) \(woeid.country)”
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
print(cell.textLabel?.text)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
print(“You selected cell #\(indexPath.row)”)
woeid = woeidList[indexPath.row] as WOEID
self.performSegueWithIdentifier(“ShowSimpleVCSegue”, sender: self)
//let woeid = woeidList[indexPath.row] as WOEID
//let aViewController: SimpleViewController = storyboard?.instantiateViewControllerWithIdentifier(“SimpleViewController”) as! SimpleViewController
//aViewController.woeid = woeid
//navigationController?.pushViewController(aViewController, animated: true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if (segue.identifier == “ShowSimpleVCSegue”) {
if let destinationVC = segue.destinationViewController as? SimpleViewController {
print(“SimpleTableViewController”)
destinationVC.woeid = woeid
}
}
}
}
MapView
import MapKit
var woeid: WOEID! // data (woeid, city, country, latitude, longitude)
@IBOutlet weak var aMapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let center = CLLocationCoordinate2D(latitude: woeid.latitude, longitude: woeid.longitude)
let span = MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)
let region = MKCoordinateRegion(center: center, span: span)
self.aMapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = center
annotation.title = woeid.city
annotation.subtitle = woeid.country
}
UIScrollView
UIScrollView
pushViewController
// SimpleVC ViewController.swift
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
//let site = sites[indexPath.row] as LectureSite
//selectedURL = site.url
//self.performSegueWithIdentifier(“ShowSimpleVCSegue”, sender: self)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
print(“You selected cell #\(indexPath.row)”)
let site = sites[indexPath.row] as LectureSite
let aViewController: SimpleViewController = storyboard?.instantiateViewControllerWithIdentifier(“SimpleViewController”) as! SimpleViewController
aViewController.name = site.name
aViewController.imageName = site.imageName
aViewController.url = site.url
navigationController?.pushViewController(aViewController, animated: true)
}
// SimpleVC SimpleViewController,swift
@IBAction func buttonPressed(sender: AnyObject) {
if let button = sender as? UIButton {
if button == aButton {
self.performSegueWithIdentifier(“ShowDetailVCSegue”, sender: self)
}
else if button == bButton {
self.performSegueWithIdentifier(“ShowOtherDetailVCSegue”, sender: self)
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if (segue.identifier == “ShowDetailVCSegue”) {
if let destinationVC = segue.destinationViewController as? DetailViewController {
destinationVC.name = name
destinationVC.imageName = imageName
}
}
else if (segue.identifier == “ShowOtherDetailVCSegue”) {
if let destinationVC = segue.destinationViewController as? OtherDetailViewController {
destinationVC.name = name
destinationVC.url = url
}
}
}