[TIL] 2021.05.26


👩🏻‍💻 Today I Learend


urlハングルコード


addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)


urlQueryAllowed (Returns the character set for characters allowed in a query URL component.) タイプでエンコードします.
let region = "종로구"
url += region.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

すべてのHTTPアクセスを許可


Source Code

<key>NSAppTransportSecurity</key>
	<dict>
		<key>NSAllowsArbitraryLoads</key>
		<true/>
	</dict>

Property List



JSONSerilizationによるJson Parsing


JSONSerialization


JSONSerilizationクラスを使用してJSONをFoundationオブジェクトに変換し、FoundationオブジェクトをJSONに変換します.

var responses = [String: Any]()
var bodys = [String: Any]()
var items = [[String : Any]]()

guard let data = data else {
    return
}

// 받아온 json을 [String: Any]로 변환하겠다.
guard let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] else{
    return
}

// 받아온 Json 파일
// {"response":
//	{"body":
//		{"items":[

// response -> body -> items에 데이터가 있을 때

responses = json["response"] as! [String : Any] 
bodys = responses["body"] as! [String : Any]
items = bodys["items"] as! [[String : Any]]

RxSwift


非同期インポートデータ


1.観測可能な作成

func loadFineDust() -> Observable<String>{
    return Observable.create{
            return Disposables.create()
    }
}

2.URLセッションを使用してデータをインポートする

func loadFineDust() -> Observable<String>{
    return Observable.create{ emitter in
        URLSession.shared.dataTask(with: URL(string: url)!) { data, res, err in
            if let err = err {
                emitter.onError(err) // error 보내기
                return
            }
            guard let data = data else {
                return
            }

            var responses = [String: Any]()
            var bodys = [String: Any]()
            var items = [[String : Any]]()

            guard let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] else{
                return
            }

            responses = json["response"] as! [String : Any]
            bodys = responses["body"] as! [String : Any]
            items = bodys["items"] as! [[String : Any]]
            let item: [String : Any] = items[0]
            let finedust: String = item["pm10Value"] as! String
            
            print(finedust)
            emitter.onNext(finedust)
            emitter.onCompleted()
            
        }.resume() // resume()을 통해 task 실행
        
        emitter.onCompleted()
        
        return Disposables.create()
    }
}

3.subscribeを使用してタスクを開始

let disposeBag = DisposeBag()

loadFineDust()
    .subscribe(onNext: { response in
        print(response)
    }, onError: { err in
        print(err)
    }).disposed(by: disposeBag) // disposBag에 담기
    

完全なコード

func loadFineDust() -> Observable<String>{
    return Observable.create{ emitter in
        URLSession.shared.dataTask(with: URL(string: url)!) { data, res, err in
            if let err = err {
                emitter.onError(err)
                return
            }
            guard let data = data else {
                return
            }

            var responses = [String: Any]()
            var bodys = [String: Any]()
            var items = [[String : Any]]()

            guard let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] else{
                return
            }

            responses = json["response"] as! [String : Any]
            bodys = responses["body"] as! [String : Any]
            items = bodys["items"] as! [[String : Any]]
            let item: [String : Any] = items[0]
            let finedust: String = item["pm10Value"] as! String
            
            print(finedust)
            emitter.onNext(finedust)
            emitter.onCompleted()
            
        }.resume()
        
        emitter.onCompleted()
        
        return Disposables.create()
    }
}

loadFineDust()
    .subscribe(onNext: { response in
        print(response)
    }, onError: { err in
        print(err)
    }).disposed(by: disposeBag)

今日の思い出


RxSWIFTを学ぶために、簡単なスモッグアプリを作りたいです.周囲の測定所を基準にスモッグデータを取得しようとしたが、思わぬ値をもたらし、どのような方法を使うか考えている.明日はAlamofireでネズミを...