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

Google Tag Managerを使ってみる


登録していきます

下記のような文言が出ます。
このコードは、次のようにページの 内のなるべく上のほうに貼り付けてください。

<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-P35PM9X');</script>
<!-- End Google Tag Manager -->

また、開始タグ の直後にこのコードを次のように貼り付けてください。

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-P35PM9X"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

早速入れてみましょう。
よくわからん。

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

x-code:jsonデータを使ってドル円計算する

まず、foundatationをimportします。

import UIKit
import Foundation

続いて、jsonを用意します。

let jsonString:String = "{\"dollaryen\":109, \"euroen\":110}"
    var code:Int = 0

prepareでjsonを取得して計算します。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let identifier = segue.identifier else {
            return
        }
        let personalData: Data = self.jsonString.data(using: String.Encoding.utf8)!
        do {
            let items = try JSONSerialization.jsonObject(with: personalData) as! Dictionary<String,Any>
            self.code = items["dollaryen"] as! Int
        } catch {
            self.code = 1
        }
        
        
        if identifier == "showResult" {
            let CalcVC = segue.destination as! CalcViewController
            CalcVC.mySales = Int(Double(self.sales.text!)! / Double(self.code))
            CalcVC.myProfit = Int(Double(self.profit.text!)! / Double(self.code))
            CalcVC.myPrice = Int(self.price.text!)!
            CalcVC.myEPS = Double(self.eps.text!)!
        }
    }

あれ、エラーが出まくってる。。。
2018-06-03 18:42:56.527314+0900 account[17768:334563] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/mac/Library/Developer/CoreSimulator/Devices/EA305F63-7A92-4933-9E03-89D80DFE7553/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2018-06-03 18:42:56.539423+0900 account[17768:334563] [MC] Reading from private effective user settings.
2018-06-03 18:42:58.597654+0900 account[17768:334563] [Common] _BSMachError: port 8c03; (os/kern) invalid capability (0x14) “Unable to insert COPY_SEND”
2018-06-03 18:43:12.349999+0900 account[17768:338350] XPC connection interrupted

buildはsucceedするが、うまくいかないです。

swiftのjson読み込み

Foundationに含まれているJSONSerializationを使う

JSON文字列をパースするには、JSONSerialization.jsonObjectを使用する。

JSONSerializationJ .jsonObject(with JSONデータ: Data, options オプション)

import Foundation 
import CryptoSwift 

let jsonString: String = "{\"id\":3932, \"company\":\"Akatsuki\"}"

var personalData: Data = jsonString.data(using: String.Encoding.utf8)!

do {
    let items = try JSONSerialization.jsonObject(with: personalData) as! Dictionary<String,Any>
    print(items["id"] as! Int)
    print(items["company"] as! String)
} catch {
    print(error)
}

3932
Akatsuki

書き方を変える。

let jsonString: String = "{\"id\":3932, \"company\":\"Akatsuki\"}"

var personalData: Data = jsonString.data(using: String.Encoding.utf8)!
let items = try JSONSerialization.jsonObject(with: personalData) as! Dictionary<String,Any>
var code:Int = items["id"] as! Int
print(code)

3932

ではXcodeに当てはめましょう。
そもそも、import Foundationって、xcodeに使えるのか?

swift foundation
https://github.com/apple/swift-corelibs-foundation
The Foundation framework defines a base layer of functionality that is required for almost all applications. It provides primitive classes and introduces several paradigms that define functionality not provided by either the Objective-C runtime and language or Swift standard library and language.

よくわかりませんが、やってみましょう。