Monday, March 11, 2019

Swift- Working with rest service

parts of a web request
    protocol    - rules
    subdomain   - point a more specifc server or etc
    domain      - unique reference to specific site
    port        -
    path        - refer specifi sub directory or file
    query param - more detail of request

    request type - GET, POST etc
    headers - key value pair which tells server how to handle the request
            response also has header which describe how the client use the information
    body    - data send or received

playgroud setup for network request
    playground default support for synchronous request. means lines runs top to bottom. so to call network requet has some changes in playground. add these lines in top
        import PlaygroundSupport

        PlaygroundPage.current.needsIndefiniteExecution = true

///////////////////////
 like in java we can seperately invoke service call and get the response as callback function. everything step by step in here. last class is using all concepts

        import Foundation
        import PlaygroundSupport


        PlaygroundPage.current.needsIndefiniteExecution = true  // make playgroud to run asnchronous request

        //let url = URL(string: "https://api.nasa.gov/planetary/apod?api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo")!
        //let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        ////    if let data = data {
        ////        print(data) // print as bytes
        ////        print(data as? NSData)// print as object
        ////    }
        //   
        //    //get as json object
        //    if let data = data,
        //        let string = String(data: data, encoding: .utf8) {
        //        print(string)
        //    }
        //    // end of return json object
        //}
        //
        //task.resume()
        ///////////////////////////////////////////////////////////

        // add query parameters seperately

        //extension URL {
        //    func withQueries(_ queries: [String: String]) -> URL? {
        //        var components = URLComponents(url: self, resolvingAgainstBaseURL: true)
        //        components?.queryItems = queries.flatMap
        //            { URLQueryItem(name: $0.0, value: $0.1) }
        //        return components?.url
        //    }
        //}
        //
        //let baseURL = URL(string: "https://api.nasa.gov/planetary/apod")!
        //let query: [String: String] = [
        //    "api_key": "NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo",
        //    "date": "2011-07-13"
        //]
        //
        //let url = baseURL.withQueries(query)!
        //let task = URLSession.shared.dataTask(with: url) { (data,
        //    response, error) in
        //    if let data = data,
        //      let string = String(data: data, encoding: .utf8) {
        //        print(string)
        //    }
        //}
        //
        //task.resume()

        ///////////////////////////////////////////////////////////
        /*josn serilization

        struct PropertyKey {
            static let title = "title"
            static let description = "explanation"
            static let url = "url"
            static let copyright = "copyright"
        }

        class PhotoInfo{
            var url : URL
            var description : String
            var title : String
            var copyright : String?
           
            init?(json: [String: Any]) {
               
                guard let title = json[PropertyKey.title] as? String,
                    let description = json[PropertyKey.description] as? String,
                    let urlString = json[PropertyKey.url] as? String,
                    let url = URL(string: urlString) else { return nil }
           
                self.url = url
                self.description = description
                self.title = title
                self.copyright = json[PropertyKey.copyright] as? String
               
            }
        }

        extension URL {
            func withQueries(_ queries: [String: String]) -> URL? {
                var components = URLComponents(url: self, resolvingAgainstBaseURL: true)
                components?.queryItems = queries.flatMap
                    { URLQueryItem(name: $0.0, value: $0.1) }
                return components?.url
            }
        }

        let baseURL = URL(string: "https://api.nasa.gov/planetary/apod")!
        let query: [String: String] = [
            "api_key": "NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo",
            "date": "2011-07-13"
        ]

        let url = baseURL.withQueries(query)!
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let data = data,
                let rawJSON = try? JSONSerialization.jsonObject(with:data),
                let json = rawJSON as? [String: String],
                let photoInfo = PhotoInfo(json:json) {
                    print(photoInfo)
               
            }
           
        //  to get normal json object use this way
        //    if let data = data,
        //        let rawJSON = try? JSONSerialization.jsonObject(with:
        //            data),
        //        let json = rawJSON as? [String: String] {
        //            print(json)
        //        }
        }

        task.resume()
         **/

        //////////////////////////
        //getting a callback with params
         /* func performLongRunningOperation(callbackFuncName: @escaping (retunFunctionParam1,retunFunctionParam2) ->
            Void) {
            // Code that performs a long running operation
            successFunc(returnParam1Value,returnParam2Value)
        }
        //example
        func callService (callbackFunc : @escaping (String, Int) -> Void) {
            callbackFunc("hi", 10)
        }
       
         // pass callback function as parameter and other parameters also
       
         func callService (urlStr : String, callbackFunc : @escaping (String, Int) -> Void) {
            callbackFunc("hi", 10)
         }
       
       
         callService (urlStr: "sss",callbackFunc : { (strVal,intVal) in
            print(strVal)
         })
       
         */

        ///////////////////////////// network request with callback
        struct PropertyKey {
            static let title = "title"
            static let description = "explanation"
            static let url = "url"
            static let copyright = "copyright"
        }

        class PhotoInfo{
            var url : URL
            var description : String
            var title : String
            var copyright : String?
           
            init?(json: [String: Any]) {
               
                guard let title = json[PropertyKey.title] as? String,
                    let description = json[PropertyKey.description] as? String,
                    let urlString = json[PropertyKey.url] as? String,
                    let url = URL(string: urlString) else { return nil }
               
                self.url = url
                self.description = description
                self.title = title
                self.copyright = json[PropertyKey.copyright] as? String
               
            }
        }

        extension URL {
            func withQueries(_ queries: [String: String]) -> URL? {
                var components = URLComponents(url: self, resolvingAgainstBaseURL: true)
                components?.queryItems = queries.flatMap
                    { URLQueryItem(name: $0.0, value: $0.1) }
                return components?.url
            }
        }

        //The @escaping keyword tells the compiler that the code in the closure will be executed after the function has returned, or has finished executing all the code.

        func callService(urlStr:String , funcCallback : @escaping (PhotoInfo) -> Void) {
            let baseURL = URL(string: urlStr)!
            let query: [String: String] = [
            "api_key": "NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo",
            "date": "2011-07-13"
            ]
           
            //here multiple conditions checking using , instear && mark
            let url = baseURL.withQueries(query)!
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let data = data,
            let rawJSON = try? JSONSerialization.jsonObject(with:data),
            let json = rawJSON as? [String: String],
            let photoInfo = PhotoInfo(json:json) {
                funcCallback(photoInfo)
                }
            }

            //                if let data = data{
            //                    print(data)
            //                    let rawJSON = try? JSONSerialization.jsonObject(with:data)
            //                    if let jsona = rawJSON as? [String: String] {
            //                        if let photoInfoa = PhotoInfo(json:jsona){
            //                            funcCallback(photoInfoa)
            //                        }
            //                    }
            //                }
           
           
            task.resume()
        }

        var urls = "https://api.nasa.gov/planetary/apod"

        callService (urlStr: urls, funcCallback:  { (photoInfoObj ) in
            print(photoInfoObj.title)
        } )

        //we can call this way also.
        callService (urlStr: urls) { (photoInfoObj ) in
            print(photoInfoObj.title)
        }

No comments:

Post a Comment