ViewController.swift #1

  • //
  • guest/
  • gronk/
  • SearchDemo/
  • SearchDemo/
  • ViewController.swift
  • View
  • Commits
  • Open Download .zip Download (9 KB)
//
//  ViewController.swift
//  SearchDemo
//
//  Created by Ralf Gronkowski on 13/10/14.
//  Copyright (c) 2014 Ralf Gronkowski. All rights reserved.
//
import UIKit

class ViewController: UITableViewController, SearchViewControllerDelegate {
    
    var files = [P4FileRev]()
    var userId:NSString?
    var ticket:NSString?
    var message:NSString?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "CellIdentifier")
        setupNavigationBar()
    }
    
    override func viewWillAppear(animated: Bool) {
        userId = NSUserDefaults.standardUserDefaults().stringForKey(SettingsKeys.namePreferenceKey)
        ticket = NSUserDefaults.standardUserDefaults().stringForKey(SettingsKeys.passwordPreferenceKey)
        super.viewWillAppear(animated)
        tableView.reloadData()
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (self.files.count == 0) {
            return 1
        }
        return files.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var image : UIImage?
        let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
        let index = UInt(indexPath.row)
        cell.textLabel?.numberOfLines = 0
        
        if self.files.isEmpty {
            cell.imageView?.image = nil
            if (message != nil) {
                cell.textLabel?.text = message
            } else {
                cell.textLabel?.text = "Tap Search to define a P4Search query"
                if ((userId) != nil){
                    cell.textLabel?.text = "Hi " + userId! + ", tap Search to define a P4Search query"
                }
            }
            cell.accessoryType = UITableViewCellAccessoryType.None
        } else {
            cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
            var image : UIImage?
            switch files[indexPath.row].getP4FileType(){
            case "text","xtext":
                image = UIImage(named: "Text")
            case "binary","xbinary","ubinary":
                if (files[indexPath.row].getFileRev().uppercaseString.rangeOfString(".JPG#", options: nil, range: nil, locale: nil) != nil){
                    image = UIImage(named: "Image")
                    
                } else if (files[indexPath.row].getFileRev().uppercaseString.rangeOfString(".MP3#", options: nil, range: nil, locale: nil) != nil){
                    image = UIImage(named: "Music")
                }
            default:
                image = nil
            }
            
            cell.imageView?.image = image
            cell.textLabel?.text = files[indexPath.row].getFileRev()
        }
        return cell
    }
    
    func setupNavigationBar() {
        let deleteBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Trash, target: self, action: "deleteButtonAction")
        let searchBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "searchButtonAction")
        navigationItem.rightBarButtonItems = [searchBarButtonItem, deleteBarButtonItem]
    }
    
    func deleteButtonAction() {
        self.files.removeAll(keepCapacity: false)
        self.tableView.reloadData()
    }
    
    func searchButtonAction() {
        let searchViewController = SearchViewController(nibName: nil, bundle: nil)
        searchViewController.delegate = self
        let navController = UINavigationController(rootViewController: searchViewController)
        presentViewController(navController, animated: true, completion: nil)
    }
    
    func didFinishTypingText(typedText: String?) {
        if typedText?.utf16Count > 0 {
            var error: NSError?
            var response: NSURLResponse?
            self.files.removeAll(keepCapacity: false)
            let urlPath = NSUserDefaults.standardUserDefaults().stringForKey(SettingsKeys.p4searchURLPreferenceKey)! + "search"
            let url: NSURL = NSURL(string: urlPath)
            let session = NSURLSession.sharedSession()
            let request = NSMutableURLRequest(URL: url)
            request.HTTPMethod = "POST"
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            let jsonString = "{\"userId\":\"\(userId!)\",\"ticket\":\"\(ticket!)\",\"queryRaw\":\"\(typedText!)\"}"
            let postdata: NSData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
            request.HTTPBody = postdata
            
            let p4SearchConnection = NSURLConnection(request: request, delegate: self)
            var data =  NSURLConnection.sendSynchronousRequest(request, returningResponse:  &response, error: &error) as NSData?
            if let actualError = error {
                NSLog("Error in P4Search connection: \(actualError.localizedDescription)")
                self.message = actualError.localizedDescription
            } else {
                var httpResponse: NSHTTPURLResponse = response as NSHTTPURLResponse!
                if httpResponse.statusCode != 200 {
                    NSLog(httpResponse.description)
                    self.message = httpResponse.description
                } else {
                    var jsonResult = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary?
                    let httpResponse: NSURLResponse = response!
                    if let actualError = error {
                        NSLog("Error in P4Search response content: \(actualError.localizedDescription)")
                        self.message = actualError.localizedDescription
                    } else {
                        let json :JSON = JSON(object: jsonResult!)
                        if json["status"]["code"].stringValue == "200" {
                            let count: Int? = json["payload"].arrayValue!.count
                            if count > 0 {
                                for index in 0...count!-1 {
                                    let depotFile = json["payload"][index]["depotFile"].stringValue
                                    let rev = json["payload"][index]["rev"].stringValue
                                    let type = json["payload"][index]["type"].stringValue
                                    let time = json["payload"][index]["time"].stringValue
                                    let action = json["payload"][index]["action"].stringValue
                                    let change = json["payload"][index]["change"].stringValue
                                    self.files.append(P4FileRev(file: depotFile, rev: rev, type: type, time: time, action: action, change: change))
                                }
                                
                                self.tableView.reloadData()
                            } else {
                                self.message = "No file revision matches your query."
                            }
                        } else {
                            NSLog(json["status"]["message"].stringValue!)
                        }
                        
                    }
                }
            }
        }
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        if !self.files.isEmpty {
            let aP4FileRev: P4FileRev = self.files[indexPath.row]
            
            switch files[indexPath.row].getP4FileType(){
            case "text","xtext":
                let textViewController = TextViewController(theP4FileRev: aP4FileRev)
                let navController = UINavigationController(rootViewController: textViewController)
                presentViewController(navController, animated: true, completion: nil)
                
            case "binary","xbinary","ubinary":
                if (files[indexPath.row].getFileRev().uppercaseString.rangeOfString(".JPG#", options: nil, range: nil, locale: nil) != nil){
                    let imageViewController = ImageViewController(theP4FileRev: aP4FileRev)
                    let navController = UINavigationController(rootViewController: imageViewController)
                    presentViewController(navController, animated: true, completion: nil)
                    
                } else if (files[indexPath.row].getFileRev().uppercaseString.rangeOfString(".MP3#", options: nil, range: nil, locale: nil) != nil){
                    let soundViewController = SoundViewController(theP4FileRev: aP4FileRev)
                    let navController = UINavigationController(rootViewController: soundViewController)
                    presentViewController(navController, animated: true, completion: nil)
                }
            default:
                NSLog("no clue what to do here")
            }
        }
    }
    
}


# Change User Description Committed
#1 10709 gronk First working example of an iOS app that searches in P4Search and displys content by retrieving it from Swarm.
There is a file JSON.swift in the project in which you need to paste some external code from here https://github.com/lingoer/SwiftyJSON/blob/master/SwiftyJSON/SwiftyJSON.swift to simplify JSON parsing. You will also need access to a running P4Search and Swarm instance if you want to run the app on a device or inside an emulator.

Coded in Swift with  XCode 6.0.1