Skip to content

Commit

Permalink
Upgrade to Swift 2.0 - WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
erinhochstatter committed Jun 11, 2015
1 parent cabea92 commit 644985f
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 110 deletions.
1 change: 1 addition & 0 deletions Harbor.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@
D0610E181A0C952E0056B8A3 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0700;
LastUpgradeCheck = 0610;
ORGANIZATIONNAME = dvm;
TargetAttributes = {
Expand Down
2 changes: 1 addition & 1 deletion Harbor/Account.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class Account : NSObject{
var projects: [Project] = []

override init(){
println("made an account")
print("made an account")
super.init()
}

Expand Down
175 changes: 94 additions & 81 deletions Harbor/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,16 @@ class AppDelegate: NSObject, NSApplicationDelegate {
var statusView: StatusView?
var projectList: [Project]?
let currentRunLoop: NSRunLoop = NSRunLoop.currentRunLoop()

func applicationDidFinishLaunching(aNotification: NSNotification) {
var aDecoder = NSCoder()

self.fetchApiKeys { (projects) -> () in
println(projects.count)
print(projects.count)
}

preferencesPaneWindow = PreferencesPaneWindow(windowNibName: "PreferencesPaneWindow")
preferencesPaneWindow?.prefManagedObjectContext = self.managedObjectContext!
println(self.managedObjectContext!)
print(self.managedObjectContext!)
statusView = StatusView()
fetchRefreshRate()
}
Expand All @@ -38,52 +37,41 @@ class AppDelegate: NSObject, NSApplicationDelegate {
func hidePopover(sender: AnyObject) {
statusView!.hidePopover()
}

func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}

// MARK: CoreData Fetch


// MARK: CoreData Fetch
func fetchRefreshRate() {
var request: NSFetchRequest = NSFetchRequest(entityName: "DMAccount")

let request: NSFetchRequest = NSFetchRequest(entityName: "DMAccount")
request.sortDescriptors = [NSSortDescriptor(key: "accountDescription", ascending: true)]

var errorPointer: NSErrorPointer = NSErrorPointer()

var projectArray: [Project] = []

if let fetchResults = managedObjectContext!.executeFetchRequest(request, error: errorPointer) as? [DMAccount] {

if fetchResults.count > 0 {

if let firstAccountRate = fetchResults.first?.refreshRate? {
setupTimer((firstAccountRate as NSString).doubleValue)
} else {
setupTimer(120)
}

do {
let account = try managedObjectContext!.executeFetchRequest(request).first as? DMAccount
if let refreshRate = account?.refreshRate {
setupTimer((refreshRate as NSString).doubleValue)
} else {
setupTimer(120)
}
} else {
println("fetch error on Popover for refreshRate / no fetchResults")
} catch let error as NSError {
print(error)
}
}

func setupTimer(refreshRate: Double) {

var loopStartTime: NSDate = NSDate(timeIntervalSinceNow: 1.0)

var timer = NSTimer(timeInterval: refreshRate, target: self, selector:"updateData", userInfo: nil, repeats: true)

let timer = NSTimer(timeInterval: refreshRate, target: self, selector:"updateData", userInfo: nil, repeats: true)
currentRunLoop.addTimer(timer, forMode: NSDefaultRunLoopMode)

println("refresh rate: \(refreshRate)")
print("refresh rate: \(refreshRate)")
}

func updateData(){
fetchApiKeys { (projects) -> () in
self.statusView!.updateUI()
println("updateData completion block")
print("updateData completion block")
}
}

Expand All @@ -96,17 +84,17 @@ class AppDelegate: NSObject, NSApplicationDelegate {

var projectArray: [Project] = []

if let fetchResults = managedObjectContext!.executeFetchRequest(request, error: errorPointer) as? [DMAccount] {
if let fetchResults = managedObjectContext!.executeFetchRequest(request) as? [DMAccount] {
for account in fetchResults {

self.retrieveProjectsForAccount(account, completionClosure: { (projects) -> () in
projectArray += projects
completionClosure(projects: projectArray)
})
println("apiKey: \(account.apiKey)")
print("apiKey: \(account.apiKey)")
}
} else {
println("fetch error on Popover for apiKey")
print("fetch error on Popover for apiKey")
}
}

Expand All @@ -121,51 +109,54 @@ class AppDelegate: NSObject, NSApplicationDelegate {

var errorPointer: NSErrorPointer = NSErrorPointer()

let fetchResults = managedObjectContext!.executeFetchRequest(request, error: errorPointer) as? [DMProject]
let fetchResults = managedObjectContext!.executeFetchRequest(request) as? [DMProject]

return fetchResults!

}

func processProject (hash: AnyObject, account: DMAccount) {
var project = Project()
project.id = Int(hash.objectForKey("id") as NSNumber)
project.repositoryName = (hash.objectForKey("repository_name") as String)
let project = Project()
project.id = Int(hash.objectForKey("id") as! NSNumber)
project.repositoryName = (hash.objectForKey("repository_name") as! String)
let dmProjectFetchResults = self.fetchProjectsWithID("\(project.id!)")

if dmProjectFetchResults.count == 0 {
project.active = true;

var dmProject: DMProject = NSEntityDescription.insertNewObjectForEntityForName("DMProject", inManagedObjectContext: self.managedObjectContext!) as DMProject
let dmProject: DMProject = NSEntityDescription.insertNewObjectForEntityForName("DMProject", inManagedObjectContext: self.managedObjectContext!) as! DMProject

dmProject.id = "\(project.id!)"
dmProject.repositoryName = project.repositoryName!
dmProject.account = account
dmProject.active = true
var errorPointer: NSErrorPointer = NSErrorPointer()
let errorPointer: NSErrorPointer = NSErrorPointer()

self.managedObjectContext?.save(errorPointer)
do {
try self.managedObjectContext?.save()
} catch var error as NSError {
errorPointer.memory = error
}

} else if dmProjectFetchResults.count == 1 {

project.active = dmProjectFetchResults.first?.active.boolValue

} else {
println("more than one project with ID: \(project.id!)")
print("more than one project with ID: \(project.id!)")
}

var projectBuildJson: Array<AnyObject> = hash.objectForKey("builds") as Array<AnyObject>
var projectBuilds: [Build] = []

let projectBuildJson: Array<AnyObject> = hash.objectForKey("builds") as! Array<AnyObject>

for buildHash in projectBuildJson {

var build = Build()
build.id = Int(buildHash.objectForKey("id") as NSNumber)
build.uuid = (buildHash.objectForKey("uuid") as String)
build.status = (buildHash.objectForKey("status") as String)
build.commitId = (buildHash.objectForKey("commit_id") as String)
build.message = (buildHash.objectForKey("message") as String)
build.branch = (buildHash.objectForKey("branch") as String)
let build = Build()
build.id = Int(buildHash.objectForKey("id") as! NSNumber)
build.uuid = (buildHash.objectForKey("uuid") as! String)
build.status = (buildHash.objectForKey("status") as! String)
build.commitId = (buildHash.objectForKey("commit_id") as! String)
build.message = (buildHash.objectForKey("message") as! String)
build.branch = (buildHash.objectForKey("branch") as! String)

project.builds.append(build)
}
Expand All @@ -174,11 +165,11 @@ class AppDelegate: NSObject, NSApplicationDelegate {
self.projectList?.append(project)

if project.builds.first!.status == "testing"{
println("\(project.repositoryName!) & \(project.builds.first!.status!)")
print("\(project.repositoryName!) & \(project.builds.first!.status!)")
self.statusView?.hasPendingBuild = false

} else if project.builds.first!.status != "success" {
println("\(project.repositoryName!) & \(project.builds.first!.status!)")
print("\(project.repositoryName!) & \(project.builds.first!.status!)")
self.statusView!.hasFailedBuild = true
}
}
Expand All @@ -189,16 +180,16 @@ class AppDelegate: NSObject, NSApplicationDelegate {

func retrieveProjectsForAccount(account: DMAccount, completionClosure: (projects: [Project]) -> ()){

var urlWithKey = "https://www.codeship.io/api/v1/projects.json?api_key=" + account.apiKey
var urlRequest: NSURLRequest = NSURLRequest(URL: NSURL(string:urlWithKey)!);
let urlWithKey = "https://www.codeship.io/api/v1/projects.json?api_key=" + account.apiKey
let urlRequest: NSURLRequest = NSURLRequest(URL: NSURL(string:urlWithKey)!);

NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue()) { (urlResponse, data, error) -> Void in
NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue()) { (urlResponse, data, error) -> Void in

var responseDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as NSDictionary
let responseDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
self.projectList = []

var projectsArray: Array<AnyObject> = responseDictionary.objectForKey("projects") as Array

let projectsArray: Array<AnyObject> = responseDictionary.objectForKey("projects") as!Array
self.statusView?.hasFailedBuild = false
self.statusView?.hasPendingBuild = false

Expand All @@ -214,46 +205,65 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}

// MARK: - Core Data stack

lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "ekh.Harbor" in the user's Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)
let appSupportURL = urls[urls.count - 1] as NSURL
return appSupportURL.URLByAppendingPathComponent("dvm.Harbor")
}()

}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Harbor", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()

}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. (The directory for the store is created, if necessary.) This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
let fileManager = NSFileManager.defaultManager()
var shouldFail = false
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."

// Make sure the application files directory is there
let propertiesOpt = self.applicationDocumentsDirectory.resourceValuesForKeys([NSURLIsDirectoryKey], error: &error)
let propertiesOpt: [NSObject: AnyObject]?
do {
propertiesOpt = try self.applicationDocumentsDirectory.resourceValuesForKeys([NSURLIsDirectoryKey])
} catch var error1 as NSError {
error = error1
propertiesOpt = nil
} catch {
fatalError()
}
if let properties = propertiesOpt {
if !properties[NSURLIsDirectoryKey]!.boolValue {
failureReason = "Expected a folder to store application data, found a file \(self.applicationDocumentsDirectory.path)."
shouldFail = true
}
} else if error!.code == NSFileReadNoSuchFileError {
error = nil
fileManager.createDirectoryAtPath(self.applicationDocumentsDirectory.path!, withIntermediateDirectories: true, attributes: nil, error: &error)
do {
dtry fileManager.createDirectoryAtPath(self.applicationDocumentsDirectory.path!, withIntermediateDirectories: true, attributes: nil)
} catch var error1 as NSError {
error = error1
} catch {
fatalError()
}
}

// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator?
if !shouldFail && (error == nil) {
coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Harbor.storedata")
if coordinator!.addPersistentStoreWithType(NSXMLStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
do {
try coordinator!.addPersistentStoreWithType(NSXMLStoreType, configuration: nil, URL: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
} catch {
fatalError()
}
}

Expand All @@ -265,14 +275,14 @@ class AppDelegate: NSObject, NSApplicationDelegate {
if error != nil {
dict[NSUnderlyingErrorKey] = error
}
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
NSApplication.sharedApplication().presentError(error!)
return nil
} else {
return coordinator
}
}()

}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
Expand All @@ -282,23 +292,23 @@ class AppDelegate: NSObject, NSApplicationDelegate {
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()

}()
// MARK: - Core Data Saving and Undo support

@IBAction func saveAction(sender: AnyObject!) {
// Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user.
if let moc = self.managedObjectContext {
if !moc.commitEditing() {
NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing before saving")
}
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
if moc.hasChanges && !moc.save() {
NSApplication.sharedApplication().presentError(error!)
}
}
}

func windowWillReturnUndoManager(window: NSWindow) -> NSUndoManager? {
// Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application.
if let moc = self.managedObjectContext {
Expand All @@ -307,7 +317,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
return nil
}
}

func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply {
// Save changes in the application's managed object context before the application terminates.

Expand All @@ -322,7 +332,10 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}

var error: NSError? = nil
if !moc.save(&error) {
do {
try moc.save()
} catch var error1 as NSError {
error = error1
// Customize this code block to include application-specific recovery steps.
let result = sender.presentError(error!)
if (result) {
Expand All @@ -348,6 +361,6 @@ class AppDelegate: NSObject, NSApplicationDelegate {
// If we got here, it is time to quit.
return .TerminateNow
}

}

Loading

0 comments on commit 644985f

Please sign in to comment.