MapKitを使ってみよう

override func viewDidLoad() {
        super.viewDidLoad()
        
        let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(35.68154,139.752498)
        
        mapView.setCenter(location, animated:true)
        
        var region:MKCoordinateRegion = mapView.region
        region.center = location
        region.span.latitudeDelta = 0.02
        region.span.longitudeDelta = 0.02
        
        mapView.setRegion(region,animated:true)
        mapView.mapType = MKMapType.hybrid
        // Do any additional setup after loading the view, typically from a nib.
    }

あれ、これ凄くね? MKMapType.hybridとか、Google Map APIそっくりじゃん。Google Map API作った人が関わってるっぽいな。Google mapよりコード量は少ない。

でもこれ、latitude, longitudenの値を取得しないとダメですな。

0.02を0.01にすると、
region.span.latitudeDelta = 0.01
region.span.longitudeDelta = 0.01

大きくなりましたね。

coreDataにdataを保存

setValueして、saveで保存する。

let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
        let newUser = NSManagedObject(entity: entity!, insertInto: context)
        
        newUser.setValue("Louis Miguel", forKey: "username")
        newUser.setValue("asdf", forKey: "password")
        newUser.setValue("1", forKey: "age")
        
        do {
            try context.save()
        } catch {
            print("Failed saving")
        }

NSEntityDescription、NSManagedObjectがunresolvedと出た時

ViewController.swift

override func viewDidLoad() {
        super.viewDidLoad()
        
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
        let newUser = NSManagedObject(entity: entity!, insertInto: context)
        // Do any additional setup after loading the view, typically from a nib.
    }

よくみたら、import UIKitだけでした。。。。。 coredataもimportします。

import UIKit
import CoreData

エラーが消えました。何だよ!

coredata : cannot import module being compiled

project nameをcoredataで作ると、
coredata : cannot import module being compiled

project nameとframeworkの重複ですね。CoreDataAppに作り直します。

viewDidLodに以下のように書く。

override func viewDidLoad() {
        super.viewDidLoad()
        
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
        let newUser = NSManagedObject(entity: entity!, insertInto: context)
    }

最初のappDelegateとは?
→アプリをつくった段階でデフォルトでつくられるファイルのひとつ。アプリ全体のライフタイムイベントを管理する

logを取ったり(どの画面で閉じたか)、ローカルのデータベースに今の状態を保存したい時とかに使っっている。

coredataでObject Graph Management(左)とPersistance(パーシスタンス)(右)の2パートに分かれていて、その二つを繋いでいるのがNSPersistantCoordinator

NSEntityDescription
Entities are to managed objects what Class is to id, or—to use a database analogy—what tables are to rows.
https://developer.apple.com/documentation/coredata/nsentitydescription?changes=_8

coredataを使う

新規にprojectを作ります。

すると、CoreDataを操作するためのフレームワークが導入
coredata.xcdatamodeldと、AppDelegate.swiftができます。
エンティティは、DBのテーブルをクラスで表す時の言葉

CoreDataのデータが更新されるタイミング

データのインスタンスは管理オブジェクトで表されますが、この管理オブジェクトを変更しても、すぐにデータベース(保存ファイル)が更新されるわけではありません。後述しますが、管理オブジェクトは管理オブジェクトコンテキストによって管理されており、この管理オブジェクトコンテキストがデータベースへの更新を行います。オブジェクトを更新した段階では、管理オブジェクトコンテキストの中では値が変わっていますが、コンテキストがデータベースへの更新を行わない限り、データベースの値は変わりません。

Entitiesが出てくる。

Add Entityでentityを追加する。

idとnameを追加する。

delegate.swfit

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "coredata")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                 
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

iosでrss

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, XMLParserDelegate {
    
    @IBOutlet weak var tableView: UITableView!
    
    let feedUrl = URL(string: "https://news.yahoo.co.jp/pickup/rss.xml")!
    var feedItems = [FeedItem]()
    
    var currentElementName : String!
    
    let ITEM_ELEMENT_NAME = "item"
    let TITLE_ELEMENT_NAME = "title"
    let LINK_ELEMENT_NAME = "link"
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.feedItems.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.subtitle, resultIdentifier: "Cell")
        let feedItem = self.feedItems[indexPath.row]
        cell.textLabel?.text = feedItem.title
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        let feedItem = self.feedItems[indexPath.row]
        UIApplication.shared.open(URL(string: feedItem.url)!, options: [:], completionHandler: nil)
    }
    
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]){
        self.currentElementName = nil
        if elementName == ITEM_ELEMENT_NAME {
            self.feedItems.append(FeedItem())
        } else {
            currentElementName = elementName
        }
    }
    
    func parser(_ parser: XMLParser, foundCharacters string: String){
        if self.feedItems.count > 0 {
            let lastItem = self.feedItems[self.feedItems.count - 1]
            switch self.currentElementName {
            case TITLE_ELEMENT_NAME:
                let tmpString = lastItem.title
                lastItem.title = (tmpString != nil) ? tmpString! + string : string
            case LINK_ELEMENT_NAME:
                lastItem.url = string
            default: break
            }
        }
    }
    
    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        self.currentElementName = nil
    }
    
    func parserDidEndDocument(_ parser: XMLParser){
        self.tableView.reloadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let parser: XMLParser! = XMLParser(contentsOf: feedUrl)
        parser.delegate = self
        parser.parse()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    

}
class FeedItem {
    var title: String!
    var url: String!
}

jsonデータの取得

import Foundation 
import CryptoSwift 

struct JsonSample : Codable {
    var high : Double
    var open : Double
    var bid : Double
    var currencyPairCode : String
    var ask : Double
    var low: Double 
} 

let listUrl = "https://www.gaitameonline.com/rateaj/getrate"

let url = URL(string: listUrl)

URLSession.shared.dataTask(with: url) { (data, response, error) in
    if error != nil {
        print(error!.localizedDescription)
    }

    guard let data = data else { return }

    let json = try? JSONDecoder().decode([JsonSample].self, from: data)
    
}.resume()
print(json.bid)

エラーになる。何故だ。。。
/tmp/EA9CF30B-2A75-422F-B05F-493561545E26.sMmRoI/main.swift:19:34: error: value of optional type ‘URL?’ not unwrapped; did you mean to use ‘!’ or ‘?’?
URLSession.shared.dataTask(with: url) { (data, response, error) in
^
!
/tmp/EA9CF30B-2A75-422F-B05F-493561545E26.sMmRoI/main.swift:29:7: error: use of unresolved identifier ‘json’
print(json.bid)

なんかうまくいかない。

let url:URL = URL(string: "")!
let task = URLSession.shared.dataTask(with: url){ data, response, error in
	if let error = error{
		print(error.localizedDescription)
		return
	}
	if let response = response as? HTTPURLResponse {
		print("response.statusCode = \(response.statusCode)")
	}
}
task.resume()

json

jasonを表示する

@IBAction func getJson(_ sender: Any) {
        let jsonString: String = "{\"id\":1, \"name\":\"Suzuki\"}"
        // JSON文字列をData型に変換
        var personalData: Data =  jsonString.data(using: String.Encoding.utf8)!
        
        do {
            // パースする
            let items = try JSONSerialization.jsonObject(with: personalData) as! Dictionary<String, Any>
            let cast = items["name"] as! String // メンバid Intにキャスト
            self.viewCenter.text = "\(cast)"
        } catch {
            print(error)
        }
        
    }