Giter VIP home page Giter VIP logo

shortenurl_ios's Introduction

shortenURL-iOS-

개요

ios와 서버와의 HTTP 요청을 공부하고, Open API를 사용한 간단한 앱을 만들어보고 싶었다. Naver Open API https://developers.naver.com/docs/common/openapiguide/
서 URL을 짧게 줄여주는 서비스가 있길래 사용해보았다.하루 2만 5천회까지 사용 가능하다.

URL만 줄여주는건 너무 간단한것 같아서, 해당 URL의 HTML을 파싱한 후에, ogtag-img를 가져왔다. 그리고 이를 이용해 history(bookmark) 페이지를 하나 더 구성해보았다.

화면

Simulator Screen Recording - iPhone 12 - 2021-06-22 at 19 44 18

Naver API

요청 방법은 네이버 api 링크에서 자세하게 설명 되어있다.

curl

curl "https://openapi.naver.com/v1/util/shorturl" \
    -d "url=http://d2.naver.com/helloworld/4874130" \
    -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" \
    -H "X-Naver-Client-Id: {애플리케이션 등록 시 발급받은 클라이언트 아이디 값}" \
    -H "X-Naver-Client-Secret: {애플리케이션 등록 시 발급받은 클라이언트 시크릿 값}" -v

curl로 응답을 받아보면

응답

{
    "message":"ok",
    "result": {
        "hash":"GyvykVAu",
        "url":"https://me2.do/GyvykVAu",
        "orgUrl":"http://d2.naver.com/helloworld/4874130"
    }
    ,"code":"200"
}

Fetching Website Data into Memory https://developer.apple.com/documentation/foundation/url_loading_system/fetching_website_data_into_memory

struct Response: Codable {
        struct Container : Codable{
            var orgUrl : String
            var url : String
            var hash : String
        }
        
        var result : Container
        let message : String
        let code: String
    }
func requestGet(query: String, completionHandler: @escaping (Bool, Any) -> Void) {
        let clientID = "클라이언트 ID"
        let clientSecret = "클라이언트 secret"
        // naver에서 애플리케이션 등록을하면 알려준다.
        let apiUrl : String = "https://openapi.naver.com/v1/util/shorturl.json?url=\(query)"
  
        guard let encodedUrl = apiUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
        // URL에 한글이 들어갈 경우를 대비해서 encoding을 해줘야한다.
        
            return
        }
        guard let url = URL(string: encodedUrl) else {
            return
        }
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.addValue(clientID, forHTTPHeaderField: "X-Naver-Client-Id")
        request.addValue(clientSecret, forHTTPHeaderField: "X-Naver-Client-Secret")
        URLSession.shared.dataTask(with: request) { data, response, error in
            guard error == nil else {
                return
            }
            guard let data = data else {
                return
            }
            guard let response = response as? HTTPURLResponse, (200 ..< 300) ~= response.statusCode else {
                return
            }
            guard let output = try? JSONDecoder().decode(Response.self, from: data) else {
                return
            }
            completionHandler(true, output)
        }.resume()
    }

shortenurl_ios's People

Contributors

regi93 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.