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!) // read
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 newDir = dir.stringByAppendingString(“data”)
print(“exportDataToPList \(newDir)”)
/*do {
try fileManager.createDirectoryAtPath(newDir, withIntermediateDirectories: true, attributes:nil)
} catch {
print(“Failed to create dir!!”)
print(error)
}*/
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)
}

}

WOEID

//
//  WOEID.swift
//  WOEID
//
//  Created by Park on 11/21/15.
//  Copyright © 2015 Park. All rights reserved.
//

import Foundation
import MapKit

class WOEID : NSObject, MKAnnotation {
var title: String? { // MKAnnotation
return description
}
var subtitle: String? { // MKAnnotation
return description
}

var code: Int64 = 0
var city: String = “”
var country: String = “”
var latitude: Double = 0.0 // MKAnnotation
var longitude: Double = 0.0 // MKAnnotation

var coordinate: CLLocationCoordinate2D { // MKAnnotation
return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}

override init() {
}

init(coder aDecoder: NSCoder!) {
self.code = aDecoder.decodeInt64ForKey(“Code”) as Int64
self.city = aDecoder.decodeObjectForKey(“City”) as! String
self.country = aDecoder.decodeObjectForKey(“Country”) as! String
self.latitude = aDecoder.decodeDoubleForKey(“Latitude”) as Double
self.longitude = aDecoder.decodeDoubleForKey(“Longitude”) as Double
}

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
}

func encodeWithCoder(coder: NSCoder!) {
coder.encodeInt64(self.code, forKey: “Code”)
coder.encodeObject(self.city, forKey: “City”)
coder.encodeObject(self.country, forKey: “Country”)
coder.encodeDouble(self.latitude, forKey: “Latitude”)
coder.encodeDouble(self.longitude, forKey: “Longitude”)
}

override 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
}
}

}

WOEIDListArchive

WOEIDListArchive

WOEIDListArchive

//
//  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 {
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
}

}

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”

aTableView.delegate = self
aTableView.dataSource = self
aTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: “cell”)

woeidList = importer.loadData() // test data

}

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)

}

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
}
}
}

}

 

//
//  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 {

@IBOutlet weak var aLabel: UILabel!
var woeid: WOEID!

@IBOutlet weak var aMapView: MKMapView!

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
print(woeid.description)
aLabel.text = woeid.description

zoomToRegion(woeid.latitude, woeid.longitude)
aMapView.addAnnotation(woeid)
aMapView.delegate = self
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func zoomToRegion(lat: CLLocationDegrees, _ lon: CLLocationDegrees) {
let regionRadius: CLLocationDistance = 1000
let location = CLLocationCoordinate2D(latitude: lat, longitude: lon)
let region = MKCoordinateRegionMakeWithDistance(location, regionRadius * 5.0, regionRadius * 7.0)

aMapView.setRegion(region, animated: true)
}

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? WOEID {
let identifier = “pin”
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure) as? UIView
}
return view
}
return nil
}

/*
// 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.
}
*/

}

 

 

SimpleViews

images

SimpleViews

//
//  ViewController.swift
//  SimpleViews
//
//  Created by Park on 11/21/16.
//  Copyright © 2016 Park. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var aTableView: UITableView!

var views = [“UIImage”, “UIImageView”,  “UIScrollView”, “UIWebView”,”UIMapView”, “UIPickerView”]

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = “Various Views”
aTableView.delegate = self
aTableView.dataSource = self
aTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: “cell”)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return views.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{

let cell: UITableViewCell = aTableView.dequeueReusableCellWithIdentifier(“cell”) as UITableViewCell!
cell.textLabel?.text = views[indexPath.row]
//cell.imageView?.image = images[indexPath.row]
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)”)

//let aViewController: SimpleViewController = storyboard?.instantiateViewControllerWithIdentifier(“SimpleViewController”) as! SimpleViewController
//aViewController.title = views[indexPath.row]
//navigationController?.pushViewController(aViewController, animated: true)
switch indexPath.row {
case 0:
self.performSegueWithIdentifier(“ShowSimpleVCSegue”, sender: self)
case 1:
self.performSegueWithIdentifier(“ShowSimpleVCSegue2”, sender: self)
case 2:
self.performSegueWithIdentifier(“ShowSimpleVCSegue3”, sender: self)
case 3:
self.performSegueWithIdentifier(“ShowSimpleVCSegue4”, sender: self)
case 4:
self.performSegueWithIdentifier(“ShowSimpleVCSegue5”, sender: self)
case 5:
self.performSegueWithIdentifier(“ShowSimpleVCSegue6”, sender: self)
default:
break
}
}

}

//
//  SimpleViewController.swift
//  SimpleViews
//
//  Created by Park on 11/21/16.
//  Copyright © 2016 Park. All rights reserved.
//

import UIKit

class SimpleViewController: UIViewController {

@IBAction func didTap(sender: AnyObject) {
self.performSegueWithIdentifier(“ShowSimpleVCSegue2”, sender: self)
}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = “UIImage”

// programmatically (with no outlet)
//let imageView = UIImageView(frame:CGRectMake(10, 50, 100, 300))
//imageView.image = UIImage(named: “smile”)
//self.view.addSubview(imageView)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}

 

//
//  SimpleViewController2.swift
//  SimpleViews
//
//  Created by Park on 11/21/16.
//  Copyright © 2016 Park. All rights reserved.
//

import UIKit

class SimpleViewController2: UIViewController {

@IBOutlet weak var aImageView: UIImageView!

@IBAction func didSwipe(sender: AnyObject) {
if aImageView.isAnimating() {
aImageView.stopAnimating()
} else {
aImageView.startAnimating()
}
}

@IBAction func didTap(sender: AnyObject) {
self.performSegueWithIdentifier(“ShowSimpleVCSegue3”, sender: self)
}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = “UIImageView”

aImageView.animationImages = [
UIImage(named: “frame1”)!,
UIImage(named: “frame2”)!,
UIImage(named: “frame3”)!,
UIImage(named: “frame4”)!,
UIImage(named: “frame5”)!
]
aImageView.animationDuration = 5
aImageView.animationRepeatCount = 0
aImageView.startAnimating()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}

 

//
//  SimpleViewController3.swift
//  SimpleViews
//
//  Created by Park on 11/21/16.
//  Copyright © 2016 Park. All rights reserved.
//

import UIKit

class SimpleViewController3: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var aScrollView: UIScrollView!
var imageView: UIImageView!
var scaleFactor: Double = 1.0

func setZoomScale() {
let imageViewSize = imageView.bounds.size
print(“imageViewSize=\(imageViewSize)”)
let aScrollViewSize = aScrollView.bounds.size
print(“scrollViewSize=\(aScrollViewSize)”)
let widthScale = aScrollViewSize.width / imageViewSize.width
let heightScale = aScrollViewSize.height / imageViewSize.height
print(“widthScale=\(widthScale) heightScale=\(heightScale)”)

aScrollView.minimumZoomScale = min(widthScale, heightScale)
aScrollView.zoomScale = 1.0
}

func centerScrollViewContents() {
let boundsSize = aScrollView.bounds.size
var contentsFrame = imageView.frame

if contentsFrame.size.width < boundsSize.width {
contentsFrame.origin.x = (boundsSize.width – contentsFrame.size.width) / 2.0
} else {
contentsFrame.origin.x = 0.0
}

if contentsFrame.size.height < boundsSize.height {
contentsFrame.origin.y = (boundsSize.height – contentsFrame.size.height) / 2.0
} else {
contentsFrame.origin.y = 0.0
}

imageView.frame = contentsFrame
}

func scrollViewDoubleTapped(recognizer: UITapGestureRecognizer) {
print(“doubletapped recognizer”)

// 1
let pointInView = recognizer.locationInView(imageView)

// 2
var newZoomScale = aScrollView.zoomScale * 1.5
newZoomScale = min(newZoomScale, aScrollView.maximumZoomScale)

// 3
let scrollViewSize = aScrollView.bounds.size
let w = scrollViewSize.width / newZoomScale
let h = scrollViewSize.height / newZoomScale
let x = pointInView.x – (w / 2.0)
let y = pointInView.y – (h / 2.0)

let rectToZoomTo = CGRectMake(x, y, w, h);

// 4
aScrollView.zoomToRect(rectToZoomTo, animated: true)
}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = “UIScrollView”

// 1
let image = UIImage(named:”RedondoBeach”)
imageView = UIImageView(image: image)
imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size:image!.size)
aScrollView.addSubview(imageView)

// 2
aScrollView.contentSize = image!.size

// 3
//let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: “scrollViewDoubleTapped:”)
//doubleTapRecognizer.numberOfTapsRequired = 2
//doubleTapRecognizer.numberOfTouchesRequired = 1
//aScrollView.addGestureRecognizer(doubleTapRecognizer)

// 4
//let scrollViewFrame = aScrollView.frame
//let scaleWidth = scrollViewFrame.size.width / aScrollView.contentSize.width
//let scaleHeight = scrollViewFrame.size.height / aScrollView.contentSize.height
//let minScale = min(scaleWidth, scaleHeight);
//aScrollView.minimumZoomScale = minScale;

// 5
//aScrollView.maximumZoomScale = 1.0
//aScrollView.zoomScale = minScale;
setZoomScale()

// 6
//centerScrollViewContents()
aScrollView.delegate = self
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

override func viewWillLayoutSubviews() {
setZoomScale()
}

func scrollViewDidScroll(scrollView: UIScrollView) {
//let foregroundHeight = self.scrollView.contentSize.height – CGRectGetHeight(self.scrollView.bounds)
//let percentageScroll = self.scrollView.contentOffset.y / foregroundHeight
//self.scrollView.contentOffset = CGPoint(x: 0, y: foregroundHeight * percentageScroll) // vertical scrolling only
aScrollView.contentOffset = CGPoint(x: aScrollView.contentOffset.x, y: aScrollView.contentOffset.y)
}

func scrollViewDidZoom(scrollView: UIScrollView) {
let imageViewSize = imageView.frame.size
let scrollViewSize = scrollView.bounds.size

let verticalPadding = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height – imageViewSize.height) / 2 : 0
let horizontalPadding = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width – imageViewSize.width) / 2 : 0

scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)
}

func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
}

//
//  SimpleViewController4.swift
//  SimpleViews
//
//  Created by Park on 11/21/16.
//  Copyright © 2016 Park. All rights reserved.
//

import UIKit

class SimpleViewController4: UIViewController {

@IBOutlet weak var aWebView: UIWebView!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = “UIWebView”

let url = NSURL(string: “http://dis.dankook.ac.kr/lectures/pmd16/”)
let requestObject = NSURLRequest(URL: url!)
aWebView.loadRequest(requestObject)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}

 

//
//  SimpleViewController5.swift
//  SimpleViews
//
//  Created by Park on 11/21/16.
//  Copyright © 2016 Park. All rights reserved.
//

import UIKit
import MapKit
import CoreLocation

class SimpleViewController5: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

@IBOutlet weak var aMapView: MKMapView!
let locationManager = CLLocationManager()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = “UIMapView”
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)
}

}

//
//  SimpleViewController6.swift
//  SimpleViews
//
//  Created by Park on 11/21/16.
//  Copyright © 2016 Park. All rights reserved.
//

import UIKit

class SimpleViewController6: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var aLabel: UILabel!
@IBOutlet weak var aPickerView: UIPickerView!

enum Activity: String {
case VeryLow = “Very Low”
case Low = “Low”
case Medium = “Medium”
case High = “High”
case VeryHigh = “Very High”
}
let aPickerElements = [“Very Low”, “Low”, “Medium”, “High”, “VeryHigh”]
var activity: Activity = Activity.VeryLow

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view, typically from a nib.
self.title = “UIPickerView”

// connect picker delegate & dataSource
aPickerView.delegate = self
aPickerView.dataSource = self
// set the default value of picker
aPickerView.selectRow(1, inComponent: 0, animated: true) // Low
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

// the number of columns in picker elements
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}

// the number of rows in picker elements
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return aPickerElements.count
}

// the element to return for row and column that’s being passed in
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return aPickerElements[row]
}

// when selected UIPickerView row, call this delegate
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch row {
case 0:
activity = Activity.VeryLow
case 1:
activity = Activity.Low
case 2:
activity = Activity.Medium
case 3:
activity = Activity.High
case 4:
activity = Activity.VeryHigh
default:
break
}
aLabel.text = activity.rawValue
}

}