matplotlib 사용

개발/Note 2022. 11. 18. 13:44
반응형

다음 코드는 matplotlib를 사용한 그래프 출력 샘플이다.

import numpy as np
import matplotlib.pyplot as plt
'''
x = np.arange(0,5)
y = x ** 2 
'''

#x= np.array([1,2,3,4,5])
x = np.arange( -5, 5, 0.1)

y1 = np.exp(x)
y2 = pow(np.exp(x), 2)
y3 = pow((1+np.exp(x)), 2)
y4 = np.exp(x) / pow((1+np.exp(x)), 2)


plt.subplot(2, 2, 1)                # nrows=2, ncols=1, index=1
#포맷 문자열 ‘ro’는 빨간색 (‘red’)의 원형 (‘o’) 마커를 의미합니다. 
# '--'은 점선을 의미. (ex. ro, o-, .-, bs, g^, r--,)
plt.plot(x,y1, 'r-')#plt.plot(x1, y1, 'r--', x2, y2, 'bs', x3, y3, 'g^')
plt.title('np.exp(x)')
plt.axis([-5, 5, 0, 5])# xmin, xmax, ymin, ymax
plt.xlabel('x')
plt.ylabel('y')

plt.subplot(2, 2, 2)                # nrows=2, ncols=1, index=2
#포맷 문자열 ‘b-‘는 파란색 (‘blue’)의 실선 (‘-‘)을 의미합니다.
plt.plot(x,y2, 'b-')
plt.title('pow(np.exp(x), 2)')
plt.axis([-5, 5, 0, 5])# xmin, xmax, ymin, ymax
plt.xlabel('x')
plt.ylabel('y')

plt.subplot(2, 2, 3)                # nrows=2, ncols=1, index=2
#포맷 문자열 ‘b-‘는 파란색 (‘blue’)의 실선 (‘-‘)을 의미합니다.
plt.plot(x,y3, 'b-')
plt.title('pow((1+np.exp(x)), 2)')
plt.axis([-5, 5, 0, 5])# xmin, xmax, ymin, ymax
plt.xlabel('x')
plt.ylabel('y')

plt.subplot(2, 2, 4)                # nrows=2, ncols=1, index=2
#포맷 문자열 ‘b-‘는 파란색 (‘blue’)의 실선 (‘-‘)을 의미합니다.
plt.plot(x,y4, 'b-')
plt.title('np.exp(x) / pow((1+np.exp(x)), 2)')
plt.axis([-5, 5, 0, 5])# xmin, xmax, ymin, ymax
plt.xlabel('x')
plt.ylabel('y')




fig1 = plt.gcf()
plt.tight_layout()
plt.show()
plt.draw()
#dpi default=100
fig1.savefig('test.png', dpi=200, facecolor='#eeeeee', edgecolor='blue')

 

반응형

'개발 > Note' 카테고리의 다른 글

Unwind Segue 사용방법  (0) 2023.01.11
랜덤 seed 초기화  (0) 2022.11.18
git 소스코드 비교  (0) 2022.02.23
20진수 변환  (0) 2021.09.16
RSA 암복호화 테스트  (0) 2021.02.05
블로그 이미지

SKY STORY

,
반응형

python에서 신경망 xor 연산 학습 샘플을 만들어 보았다.

# neural network xor


import math
import random
from datetime import datetime

import matplotlib.pyplot as plt
import numpy as np

# 네트워크의 학습 속도
LEARNING_RATE = 1.414213562

MOMENTUM = 0.25

# 훈련 데이타
TRAINING_DATA = [
    [1.0, 0.0],
    [1.0, 1.0],
    [0.0, 1.0],
    [0.0, 0.0]
]

# 타겟 값
TARGET_DATA = [
    1.0, 
    0.0, 
    1.0, 
    0.0
]

MAX_LAYERS = 4
MAX_WEIGHTS = 9
MAX_EPOCHS = 10000 

# 가중치
weights = [0. for i in range(MAX_WEIGHTS)] # [0] * 9
gradients = [0. for i in range(MAX_WEIGHTS)] # [0] * 9
error = [0. for i in range(MAX_LAYERS)] # [0] * 4  #error = np.zeros(4, dtype='f')

update_weights = [0. for i in range(MAX_WEIGHTS)] # [0] * 9
prev_weight_update = [0. for i in range(MAX_WEIGHTS)] # [0] * 9
rmse_array_error = [0. for i in range(MAX_EPOCHS)] # [0] * 10000  # 각 세대별 RMSE 에러 값

bias1 = 1.0
bias2 = 1.0
bias3 = 1.0
h1 = 0.0
h2 = 0.0
output_neuron = 0.0
derivative_O1 = 0.0
derivative_h1 = 0.0
derivative_h2 = 0.0
sum_output = 0.0
sum_h1 = 0.0
sum_h2 = 0.0


# sum_output
graph_sum_output = [[0. for i in range(MAX_EPOCHS)] for j in range(MAX_LAYERS)]

# 그래프 출력을 위한 버퍼 
graph_derivative_O1 = [[0. for i in range(MAX_EPOCHS)] for j in range(MAX_LAYERS)]
graph_derivative_h1 = [[0. for i in range(MAX_EPOCHS)] for j in range(MAX_LAYERS)]
graph_derivative_h2 = [[0. for i in range(MAX_EPOCHS)] for j in range(MAX_LAYERS)]



'''
                bias1   bias3
                  |      |
                  w4     w8
                  |      |
 input1 --w0 --- h1      |
        \       /  \     |
         \     /    w6   |
          w1  /      \   |
            \/         output
            /\        /
          w2  \      w7
          /    \    /
         /      \  /
 input2 --w3----- h2
                  |
                  w5
                  |
                bias2
'''


def sigmoid_function(x) :
    sigmoid = 1.0 / ( 1.0 + np.exp(-x) )
    return sigmoid

# 변수 초기화 
def initialize():
    global prev_weight_update, update_weights, gradients, error, rmse_array_error
    for i in range(MAX_WEIGHTS):
        prev_weight_update[i] = 0.0
        update_weights[i] = 0.0
        gradients[i] = 0.0
    for i in range(MAX_LAYERS):
        error[i] = 0.0
    for i in range(MAX_EPOCHS):
        rmse_array_error[i] = 0.0

def generate_weights() :
    global weights
    for i in range(MAX_WEIGHTS):
        weights[i] = random.uniform(-1.0, 1.0)
        print("weight[",i,"] = ", weights[i])

def train_neural_net() :
    global rmse_array_error, error
    # 세대(학습 횟수)
    epoch = 0
    while epoch < MAX_EPOCHS :
        for i in range(MAX_LAYERS):
            calc_hidden_layers(i)
            calc_output_neuron()
            graph_sum_output[i][epoch] = sum_output
            calc_error(i)
            calc_derivatives(i)
            graph_derivative_O1[i][epoch] = derivative_O1
            graph_derivative_h1[i][epoch] = derivative_h1
            graph_derivative_h2[i][epoch] = derivative_h2
            calc_gradients(i)
            calc_updates()

        # RMSE 에러 값
        sum = math.pow(error[0], 2) + math.pow(error[1], 2) + math.pow(error[2], 2) + math.pow(error[3], 2)
        rmse_error = math.sqrt( sum / MAX_LAYERS )
        print("RMSE error: ", rmse_error)
        rmse_array_error[epoch] = rmse_error

        # 세대        
        epoch = epoch + 1
        print("epoch:", epoch)

        
        # 예외 처리 - 처음부터 다시 
        if epoch > 4000 and rmse_error > 0.3:
            epoch = 0
            initialize()
            generate_weights()


def calc_hidden_layers(x):
    global sum_h1, sum_h2, h1, h2, weights, bias1, bias2
    sum_h1 = (TRAINING_DATA[x][0] * weights[0]) + (TRAINING_DATA[x][1] * weights[2]) + (bias1 * weights[4])
    sum_h2 = (TRAINING_DATA[x][0] * weights[1]) + (TRAINING_DATA[x][1] * weights[3]) + (bias2 * weights[5])
    h1 = sigmoid_function(sum_h1)
    h2 = sigmoid_function(sum_h2)

def calc_output_neuron():
    global sum_output, h1, h2, weights, bias3, output_neuron
    sum_output = (h1 * weights[6]) + (h2 * weights[7]) + (bias3 * weights[8])
    output_neuron = sigmoid_function(sum_output)

def calc_error(x):
    global error, output_neuron
    error[x] = output_neuron - TARGET_DATA[x]

def calc_derivatives(x):
    global derivative_O1, derivative_h1, derivative_h2, sum_h1, sum_h2, weights, sum_output, error
    derivative_O1 = -error[x] * ( np.exp(sum_output) / math.pow((1 + np.exp(sum_output)), 2) )
    derivative_h1 = ( np.exp(sum_h1) / math.pow((1 + np.exp(sum_h1)), 2) ) * weights[6] * derivative_O1
    derivative_h2 = ( np.exp(sum_h2) / math.pow((1 + np.exp(sum_h2)), 2) ) * weights[7] * derivative_O1

def calc_gradients(x):
    global gradients, derivative_O1, derivative_h1, derivative_h2, h1, h2, bias1, bias2,bias3
    gradients[0] = sigmoid_function(TRAINING_DATA[x][0]) * derivative_h1
    gradients[1] = sigmoid_function(TRAINING_DATA[x][0]) * derivative_h2
    gradients[2] = sigmoid_function(TRAINING_DATA[x][1]) * derivative_h1
    gradients[3] = sigmoid_function(TRAINING_DATA[x][1]) * derivative_h2
    gradients[4] = sigmoid_function(bias1) * derivative_h1
    gradients[5] = sigmoid_function(bias2) * derivative_h2
    gradients[6] = h1 * derivative_O1
    gradients[7] = h2 * derivative_O1
    gradients[8] = sigmoid_function(bias3) * derivative_O1

def calc_updates():
    global update_weights, gradients, prev_weight_update
    for i in range(MAX_WEIGHTS):
        update_weights[i] = (LEARNING_RATE * gradients[i]) + (MOMENTUM * prev_weight_update[i])
        prev_weight_update[i] = update_weights[i]
        weights[i] = weights[i] + update_weights[i]


def save_data():
    global rmse_array_error, weights
    with open('errorData1.txt', 'w', encoding='utf-8') as f:
        for i in range(MAX_EPOCHS):
            line = '%d   %s' % (i, rmse_array_error[i])
            f.write(line) # f.write('\n'.join(lines))
            f.write('\n') # f.writelines('\n')
    
    with open('weight_data1.txt', 'w', encoding='utf-8') as f:
        for i in range(MAX_WEIGHTS):
            line = '%d   %s' % (i, weights[i])
            f.write(line)
            f.write('\n')

def start_input():
    global weights, sum_h1, sum_h2, h1, h2, bias1, bias2, bias3, sum_output, output_neuron

    choice = 'y'
    while True:
        if choice == 'Y' or choice == 'y':
            data1 = input("enter data 1: ")
            if data1.isnumeric() == False :
                continue
            data2 = input("enter data 2: ")
            if data2.isnumeric() == False :
                continue

            sum_h1 = (float(data1) * weights[0]) + (float(data2) * weights[2]) + (bias1 * weights[4])
            sum_h2 = (float(data1) * weights[1]) + (float(data2) * weights[3]) + (bias2 * weights[5])
            h1 = sigmoid_function(sum_h1)
            h2 = sigmoid_function(sum_h2)
            
            sum_output = (h1 * weights[6]) + (h2 * weights[7]) + (bias3 * weights[8])
            output_neuron = sigmoid_function(sum_output)
            print('output = ', output_neuron)

            choice = input('Again? (y/n) : ')
        else:
            print('exit')
            break




initialize()
generate_weights()
train_neural_net()

save_data()
start_input()







# ===============================================================

# sigmoid
x = np.arange( -10.0, 10.0, 0.1)
y = 1.0 / (1.0 + np.exp(-x))
plt.subplot(2, 3, 1)                
plt.plot(x,y, 'r-')#plt.plot(x1, y1, 'r--', x2, y2, 'bs', x3, y3, 'g^')
plt.title('sigmoid')# 1.0 / (1.0 + np.exp(-x))
plt.axis([-10.0, 10.0, 0, 1.0])# xmin, xmax, ymin, ymax
plt.xlabel('x')
plt.ylabel('y')

# sum_output
x2 = np.arange( 0.0, 10000.0, 1.0)
y2 = graph_sum_output[0]
plt.subplot(2, 3, 2)               
plt.plot(x2,y2, 'r-')#plt.plot(x1, y1, 'r--', x2, y2, 'bs', x3, y3, 'g^')
plt.title('sum_output')
plt.axis([0.0, 10000.0, -0.2, 5.0])# xmin, xmax, ymin, ymax
plt.xlabel('epoch')
plt.ylabel('sum_output')

# rmse_array_error
x2 = np.arange( 0.0, 10000.0, 1.0)
y2 = rmse_array_error
plt.subplot(2, 3, 3)               
plt.plot(x2,y2, 'r-')#plt.plot(x1, y1, 'r--', x2, y2, 'bs', x3, y3, 'g^')
plt.title('RMSE Error')
plt.axis([0.0, 10000.0, 0.0, 1.0])# xmin, xmax, ymin, ymax
plt.xlabel('epoch')
plt.ylabel('RMSE error')


# derivative_O1
x3 = np.arange( 0.0, 10000.0, 1.0)
y3 = graph_derivative_O1[0] 
plt.subplot(2, 3, 4)              
plt.plot(x3,y3, 'r-')#plt.plot(x1, y1, 'r--', x2, y2, 'bs', x3, y3, 'g^')
plt.title('derivative_O1')
plt.axis([0.0, 10000.0, -0.05, 0.15])# xmin, xmax, ymin, ymax
plt.xlabel('epoch')
plt.ylabel('derivative_O1')

# derivative_h1
x4 = np.arange( 0.0, 10000.0, 1.0)
y4 = graph_derivative_h1[0]
plt.subplot(2, 3, 5)                
plt.plot(x4,y4, 'r-')#plt.plot(x1, y1, 'r--', x2, y2, 'bs', x3, y3, 'g^')
plt.title('derivative_h1')
plt.axis([0.0, 10000.0, -0.05, 0.15])# xmin, xmax, ymin, ymax
plt.xlabel('epoch')
plt.ylabel('derivative_h1')

# derivative_h2
x5 = np.arange( 0.0, 10000.0, 1.0)
y5 = graph_derivative_h2[0]
plt.subplot(2, 3, 6)                
plt.plot(x5,y5, 'r-')#plt.plot(x1, y1, 'r--', x2, y2, 'bs', x3, y3, 'g^')
plt.title('derivative_h2')
plt.axis([0.0, 10000.0, -0.05,0.15])# xmin, xmax, ymin, ymax
plt.xlabel('epoch')
plt.ylabel('derivative_h2')


fig1 = plt.gcf()
plt.tight_layout()
plt.show()
plt.draw()
fig1.savefig('nn_xor_derivative.png', dpi=200, facecolor='#eeeeee', edgecolor='blue')


결과 그래프는 다음과 같다.


#----------------------------------------------------------------
weight_data1.txt

0 -4.749828824761969
1 -3.5287652884908254
2 -4.747508485076842
3 -3.5276048615858935
4 1.816578868741784
5 5.375092217625854
6 -13.742230835984616
7 13.712746773928748
8 -6.530714643755955



#----------------------------------------------------------------
errorData1.txt

0 0.5424391889837473
1 0.5331220459189032
2 0.5304319567906218

10 0.5274519675428608

100 0.5198658296518869

200 0.5155776076419263

300 0.5046587144670703

400 0.4791696883760997

1000 0.09849463249517668

2000 0.03296842320700676

3000 0.02307589090605272

9999 0.010292985691909057



반응형

'개발 > AI,ML,ALGORITHM' 카테고리의 다른 글

MNIST 데이터셋을 이미지 파일로 복원  (0) 2023.07.19
MNIST 데이터셋 다운로드  (0) 2023.07.19
2D 충돌처리  (0) 2020.12.12
Generic algorithm  (0) 2020.05.19
neural network  (0) 2020.05.19
블로그 이미지

SKY STORY

,
반응형

NSURLSessionTask 를 사용하여 파일을 로딩할 경우
최초 1회 이후 캐싱되어 웹에서 json파일을 변경해도 반영되지 않는다.
그래서 다음과같이 캐싱을 비활성화 하여 파일 변경사항이 즉시 반영되도록 하였다.

// 테스트용 json파일 다운로드
let urlString = "https://www.test.com/data/info.json"

// NSURLSessionTask 캐싱 비활성화
let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalCacheData
config.urlCache = nil
let session = URLSession(configuration: config)

session.dataTask(with: URL(string: urlString)!) { (data, response, error) -> Void in
    if error == nil && data != nil {
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: Any]
            print("\(json)")
	
        } catch {
            print("Something went wrong")
        }
    }
}.resume()

 

반응형
블로그 이미지

SKY STORY

,
반응형

네이티브 UIScrollView 화면에서 스크린샷 구하는 방법에 대해 알아보자.

일반적으로 스크린샷을 구해보면 화면에 보이는 부분만

구해지며 숨겨진 영역은 흰색화면으로 출력된다. (iOS 13.0이상 에서 생기는 버그)

extension UIScrollView {
    func screenshot() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(contentSize, false, 0.0)
        let savedContentOffset = contentOffset
        let savedFrame = frame
        defer {
            UIGraphicsEndImageContext()
            contentOffset = savedContentOffset
            frame = savedFrame
        }
        contentOffset = .zero
        frame = CGRect(x: 0, y: 0, width: contentSize.width, height: contentSize.height)
        guard let ctx = UIGraphicsGetCurrentContext() else {
            return nil
        }
        layer.render(in: ctx)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        return image
    }
}

이를 위해 UIScrollView를 부모로 부터 Layout 컨텐츠를 비활성하고 스크린샷 이미지를 구하고 다시

원래대로 활성화 시켜주는 방법으로 해결 가능하다.

extension UIScrollView {
    func screenshot() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(contentSize, false, 0.0)
        let savedContentOffset = contentOffset
        let actualConstraints = relatedConstraints()
        NSLayoutConstraint.deactivate(actualConstraints)
        translatesAutoresizingMaskIntoConstraints = true
        frame = CGRect(x: 0, y: 0, width: contentSize.width, height: contentSize.height)
        contentOffset = .zero
        defer {
            UIGraphicsEndImageContext()
            translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate(actualConstraints)
            superview?.layoutIfNeeded()
            contentOffset = savedContentOffset
        }
        guard let ctx = UIGraphicsGetCurrentContext() else {
            return nil
        }
        layer.render(in: ctx)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        return image
    }
}


extension UIView {
    func relatedConstraints() -> [NSLayoutConstraint] {
        var constraints = self.constraints
        var parent = superview
        while parent != nil {
            constraints.append(contentsOf: parent!.constraints.filter { $0.firstItem === self || $0.secondItem === self })
            parent = parent!.superview
        }
        return constraints
    }
    
    class func getAllSubviews<T: UIView>(from parenView: UIView) -> [T] {
        return parenView.subviews.flatMap { subView -> [T] in
            var result = getAllSubviews(from: subView) as [T]
            if let view = subView as? T { result.append(view) }
            return result
        }
    }
	
    class func getAllSubviews(from parenView: UIView, types: [UIView.Type]) -> [UIView] {
        return parenView.subviews.flatMap { subView -> [UIView] in
            var result = getAllSubviews(from: subView) as [UIView]
            for type in types {
                if subView.classForCoder == type {
                    result.append(subView)
                    return result
                }
            }
            return result
        }
    }
	
    func getAllSubviews<T: UIView>() -> [T] { return UIView.getAllSubviews(from: self) as [T] }
    func get<T: UIView>(all type: T.Type) -> [T] { return UIView.getAllSubviews(from: self) as [T] }
    func get(all types: [UIView.Type]) -> [UIView] { return UIView.getAllSubviews(from: self, types: types) }
}


/*
// 현재 뷰의 하위뷰 중 UIScrollView를 구한다.
if let scrollView = self.view.get(all: UIScrollView.self).first {
    // 스크롤뷰의 모든 컨텐츠가 나오도록 스크린샷 이미지로 반환한다.
    let image = scrollView.screenshot()
    
    // 주어진 이미지를 공유
    DispatchQueue.main.async {
        let imageToShare = [ image ]
        let activityVC = UIActivityViewController(activityItems: imageToShare as [Any], applicationActivities: nil)
        self.present(activityVC, animated: true, completion: nil)
    }
}
*/

 

반응형
블로그 이미지

SKY STORY

,
반응형

문자열 숫자에 3자리마다 콤마를 넣을 때 사용할 함수를 알아보자

extension String {
    var commas: String {
        guard self.isEmpty == false else { return "" }
        // 이미 ','가 존재하면 제거 
        let str = replacingOccurrences(of: ",", with: "", options: .literal, range: nil)
        
        let numFmt = NumberFormatter()
        numFmt.numberStyle = .decimal
        // 포멧 적용 소수점 이하 자릿수
        // 소수점 이하 최대 7자리까지만 적용되며 반올림 된다.
        numFmt.maximumFractionDigits = 7
        // 현재 문자열 숫자를 NSNumber객체로 변환
        let num = numFmt.number(from: str)
        // 3자릿수마다 콤마 삽입
        return numFmt.string(for: num) ?? str
    }
}

/*
let s = "1234567890.123456789".commas
print("\(s)")

let s2 = "1234567890".commas
print("\(s2)")

결과 : 
1,234,567,890.1234567
1,234,567,890
*/

소수점 이하 7자리까지만 지원된다는 문제가 있지만 일반적으로 사용하는데 문제없을 듯하다. 

maximumFractionDigits 참조 :

https://developer.apple.com/documentation/foundation/numberformatter/1415364-maximumfractiondigits

 

만약 소수점 이하 자릿수 제한 없이 구현해야 한다면 다음 함수를 이용하자.

extension String {
	var commas : String {
        guard self.isEmpty == false else { return "" }
        let str = replacingOccurrences(of: ",", with: "", options: .literal, range: nil)
        // 소수점을 기준으로 토큰 분리
        let strArr = str.components(separatedBy: ".")
        guard strArr.count > 0 else { return self }
        guard strArr[0].isNumber else { return self }
        let numFmt = NumberFormatter()
        numFmt.numberStyle = .decimal
        let num = numFmt.number(from: strArr[0])
        var numStr = numFmt.string(from: num) ?? strArr[0]
        if strArr[1].isEmpty == false {
            numStr.append(".\(strArr[1])")
        }
        return numStr
    }
}

/*
let s = "1234567890.123456789".commas
print("\(s)")

결과 : 
1,234,567,890.123456789
*/

소수점 이하 자릿수 제한 없이 사용 가능하다.

 

반응형
블로그 이미지

SKY STORY

,
반응형

유니버셜링크 적용 시 도메인 루트에 AASA(apple-app-site-association)파일을 생성하여
관련정보를 설정해야 한다. 개발 중에 주의할 점은 이 파일을 다운받게 되면 캐싱되어
그 이후 계속적으로 캐싱된 파일이 사용되므로 중간에 내용을 바꾸어도 적용되지 않는다.
이 상황을 모르고 작업하다보면 원인파악에 많은 시간을 낭비할 수 있으므로 다음 내용을 숙지하기 바란다.

AASA파일을 다운받아 캐싱되는 경우
1. 앱 최초 설치 시 AASA파일 인스톨할 경우 (앱스토어 다운로드)
2. 앱 스토어 업데이트로 인한 인스톨 (앱 업데이트)

위 두가지 이외는 더 이상 다운로드 되지 않을 수 있으므로 중간에 해당 파일을 수정했을 경우
정상동작하지 않고 이전 파일(캐싱된 파일)로 적용된다.
또한 AASA파일을 다운로드가 안될경우(방화벽 또는 도메인 문제 등.) 역시 정상 동작되지 않으므로
해당 파일 다운로드가 가능한지 체크한다.
개발중 AASA파일 갱신으로 인하여 캐싱된 파일을 강제 업데이트 할 경우 다음과정을 통해 업데이트하길 바란다.

1. 디바이스에서 앱 제거
2. 디바이스 재시작
3. 앱 재설치
4. 1~3번을 2~3번 재시도
5. 앱 내에서 AASA파일이 다운로드 성공인지 확인.

AASA 파일 다운로드 성공 확인 방법 :
- 휴대폰의 노트앱 실행
- 링크를 노트에 붙여넣기
- 해당 링크를 2초이상 누르고 있으면 드롭 다운 메뉴가 뜨는데 
  메뉴리스트에 '링크 열기' 표시되지 않고 '[앱이름] 으로 열기'가 
  표시되면 성공이다.
  
  ex) AASA 파일 링크
  https://myapp.page.link/apple-app-site-association

  ex) AASA 파일 내용 
  {"applinks":{"apps":[],"details":[{"appID":"ABCDEF2TH3.com.company.myapp","paths":["NOT /_/*","/*"]}]}}



반응형

'개발 > iOS' 카테고리의 다른 글

UIScrollView 스크린샷 만들기  (0) 2022.10.24
문자열 숫자에 콤마 넣기  (0) 2022.10.14
웹 저장 데이터 (Cookie, Cache) 삭제  (0) 2021.09.24
버전분기 샘플  (0) 2021.08.02
시뮬레이터 분기  (0) 2021.08.02
블로그 이미지

SKY STORY

,
반응형

현재 작업중인 소스코드가 git에 마지막으로 commit된 소스코드와

비교를 해야할 경우가 종종 발생한다.

이럴경우 이전 commit코드와 비교하여 추가,삭제 및 수정된 부분을

알 수 있도록 보여주는 기능(Code Review)을 사용하도록 하자. 

 

View / Show Code Review

Shift + Option + Command + Enter

 

'Code Review' 가 활성화되면 Xcode 우상단 아이콘(1번)이 아래 그림과 같이 변경된다.

또한 우측 목록 아이콘을 클릭하여 Inline, Side By Side 비교방법(2번)을 선택할 수 있다.

 

Inline Comparision - 현재 소스코드에서 저장된 코드와의 비교

다음과 같이 변경된 부분은 좌측 라인번호에 파란색 마크가 생긴다.

 

Side By Side Comparision - 현재 소스코드와 저장된 코드를 화면분할 출력하여 비교

다음과 같이 현재 코드와 저장된 코드를 둘다 출력하여 변경된 부분을 비교해 준다.

 

 

반응형

'개발 > Note' 카테고리의 다른 글

랜덤 seed 초기화  (0) 2022.11.18
matplotlib 사용  (0) 2022.11.18
20진수 변환  (0) 2021.09.16
RSA 암복호화 테스트  (0) 2021.02.05
RSA key 파일 생성  (0) 2021.02.05
블로그 이미지

SKY STORY

,
반응형

하이브리드 앱을 제작하다 보면 웹페이지에서 저장한 데이터(쿠키, 캐시)를

삭제해야 하는 경우가 생긴다.

하지만 모든 저장 데이터를 삭제하다 보면 다른 웹 페이지에 저장된 데이터까지

모두 삭제되어 예외사항이 발생할 수 있다.

 

특정 페이지에서 저장된 데이터만 삭제하는 코드를 알아보자.

// 다음과 같이 displayName을 이용하여 특정 데이터만 삭제.
WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
	WKWebsiteDataStore.default().removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(),
                                            for: records.filter { $0.displayName.contains("mytest.com") },
                                            completionHandler: {
                                                print("\("delete website data")")
                                            })
}

 

다음은 모든 캐시데이터 및 특정 도메인 쿠키 삭제

// 모든 캐시데이터 삭제
let cacheDataTypes : Set<String> = [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache]
let date = Date(timeIntervalSince1970: 0)
WKWebsiteDataStore.default().removeData(ofTypes: cacheDataTypes,
                                        modifiedSince: date ,
                                        completionHandler: {
                                            print("delete cache data")
                                        })
                                        
                                        
                                        
// 특정 도메인 쿠키만 삭제
let cookieDataType : Set<String> = [WKWebsiteDataTypeCookies]
WKWebsiteDataStore.default().fetchDataRecords(ofTypes: cookieDataType) { records in
    WKWebsiteDataStore.default().removeData(ofTypes: cookieDataType,
                                            for: records.filter { $0.displayName.contains("mytest.com") },
                                            completionHandler: {
                                                print("delete cookie data")
                                            })
}

 

웹 저장 데이터 로그 출력 

// 쿠키 정보 보기 
WKWebsiteDataStore.default().httpCookieStore.getAllCookies { cookies in
    for cookie in cookies {
        print("cookie : \(cookie)")
    }
}



/* 
출력 로그 :
cookie : <NSHTTPCookie
	version:1
	name:JSESSIONID
	value:43C2101193D26FDE7F2DB61D86E15B0E
	expiresDate:'(null)'
	created:'2021-09-17 00:06:31 +0000'
	sessionOnly:TRUE
	domain:www.mytest.com
	partition:none
	sameSite:none
	path:/
	isSecure:FALSE
	isHTTPOnly: YES
 path:"/" isSecure:FALSE isHTTPOnly: YES>
 */

 

 

 

 

반응형

'개발 > iOS' 카테고리의 다른 글

문자열 숫자에 콤마 넣기  (0) 2022.10.14
유니버셜 링크(Universal Links) 문제점 해결  (0) 2022.07.21
버전분기 샘플  (0) 2021.08.02
시뮬레이터 분기  (0) 2021.08.02
Foreground 이벤트 받기  (0) 2021.08.02
블로그 이미지

SKY STORY

,