How to create a simple web service consuming iOS app using swift program



    1. Create a web service request using NSURLConnection delegate

           var urlString:NSString = "Webservice URL"
        
           var url : NSURL = NSURL(string: urlString)
        
           var request:NSURLRequest = NSURLRequest(URL: url)
        
           var connection:NSURLConnection = NSURLConnection(request: request, delegate: self)
        
           connection.start()

    2.  Parse the response in connectionDidFinishLoading(connection: NSURLConnection!) 
         method

           func connectionDidFinishLoading(connection: NSURLConnection!){
        
              var jsonResult : NSDictionary
                   NSJSONSerialization.JSONObjectWithData(self.responseData, options: nil, error: nil) as                       NSDictionary
        
                if jsonResult.count>0 && jsonResult["list"].count>0 {
        
                          weatherList = jsonResult ["list"] as NSArray
                           println("Result \(weatherList)")
            
                         for var i=0; i < weatherList.count; i++ {
                
                                     var weathersDict:NSDictionary = weatherList[i] as NSDictionary
                
                                      var weatherIconsArray:NSArray = weathersDict["weather"] as NSArray
                
                                      for var j=0; j < weatherIconsArray.count; j++ {
                                            var null:NSNull = NSNull()
                                            weatherIcons.addObject(null)
                                      }
                     }

               println("icon count\(self.weatherIcons.count)")
             
                //Append to tableview
               self.tableView.reloadData()
               asyncWeatherIconDownload()
        }

    }

3. Load the weather icons async using NSOperation Queue

      func asyncWeatherIconDownload(){
        
              var num:Int = 0
              var operationQueue:NSOperationQueue = NSOperationQueue()
              operationQueue.addOperationWithBlock({
               for var i = 0; i < self.weatherList.count; i++ {
                
                     var weathersDict:NSDictionary = self.weatherList[i] as NSDictionary
                
                     var weatherArray:NSArray = weathersDict["weather"] as NSArray
                
                     for var j = 0; j < weatherArray.count; j++ {
                          var weatherIconsDict:NSDictionary = weatherArray[j] as NSDictionary
                          var icons:NSString = weatherIconsDict["icon"] as String
                          var iconURL:NSString = "http://openweathermap.org/img/w/\(icons).png"
                          println("iconURL \(iconURL)")
                          var url:NSURL = NSURL(string: iconURL)
                          var urlRequest:NSURLRequest = NSURLRequest(URL: url)
                          var loadedData:NSData = NSURLConnection.sendSynchronousRequest(urlRequest,                             returningResponse:nil , error:nil)
                    
                           if loadedData != nil{
                        
                               var image:UIImage = UIImage(data: loadedData)
                               var mainOperationQueue:NSOperationQueue = NSOperationQueue.mainQueue()
                                     mainOperationQueue.addOperationWithBlock({
                                self.weatherIcons.replaceObjectAtIndex(num, withObject: image)
                                num++
                                self.tableView.reloadData()
                         })
                     }
                }
                }
            })
        }

4. Display the parsed content to tableView

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: 
NSIndexPath!) -> UITableViewCell! {
        
        /* //Default Tableview Cell
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle,       
        reuseIdentifier: "Cell")
        
        cell.text = "Row #\(indexPath.row)"
        cell.detailTextLabel.text = "Subtitle #\(indexPath.row)"
        return cell
        */
        
        // Add the following in cellForRowIndexPath
        
        var cell:WeatherTableViewCell? = self.tableView.dequeueReusableCellWithIdentifier("Cell") as?         WeatherTableViewCell
        
        var name:NSDictionary = self.weatherList[indexPath.row] as NSDictionary
        var weatherArray:NSArray = name["weather"] as NSArray
        var weatherDescriptionDict:NSDictionary = weatherArray[0] as NSDictionary
        
        cell!.weatherName.text = name["name"] as String
        cell!.descriptionLbl.text = weatherDescriptionDict ["description"] as NSString
        
        if self.weatherIcons.objectAtIndex(indexPath.row) as NSObject != NSNull() {
            
            cell!.weatherIcon.image = self.weatherIcons.objectAtIndex(indexPath.row) as UIImage
        }
        return cell;
        
    }

Comments