Upgrade to Pro — share decks privately, control downloads, hide ads and more …

MVC-N Discussion

MVC-N Discussion

A discussion about proper networking in your iOS based application

Marcus S. Zarra

March 10, 2016
Tweet

Other Decks in Technology

Transcript

  1. MyUIViewController Network Request Network Request OtherUIViewController Network Request Network Request

    ThirdUIViewController Network Request Network Request Controller Layer FourthUIViewController Network Request Network Request Core Data Anti-Pattern
  2. NetworkController NR NR NR NR NR NR Network Controller Dependency

    Injection Singleton AppDelegate property class NetworkController: NSObject { } let queue = NSOperationQueue() var mainContext: NSManagedObjectContext? func requestMyData() func requestMyData() -> NSFetchedResultsController func requestMyData(completion: (Void) -> Bool)
  3. NetworkController NR NR NR NR NR NR Network Controller class

    MyNetworkRequest: NSOperation { var context: NSManagedObjectContext? init(myParam1: String, myParam2: String) }
  4. class MyNetworkRequest: NSOperation { var context: NSManagedObjectContext? private var innerContext:

    NSManagedObjectContext? private var task: NSURLSessionTask? private let incomingData = NSMutableData() init(myParam1: String, myParam2: String) { super.init() //set some parameters here } var internalFinished: Bool = false override var finished: Bool { get { return internalFinished } set (newAnswer) { willChangeValueForKey("isFinished") internalFinished = newAnswer didChangeValueForKey("isFinished") } } }
  5. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition)

    -> Void) { if cancelled { finished = true sessionTask?.cancel() return } //Check the response code and react appropriately completionHandler(.Allow) } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if cancelled { finished = true sessionTask?.cancel() return } incomingData.appendData(data) }
  6. func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if

    cancelled { finished = true sessionTask?.cancel() return } if error != nil { self.error = error log("Failed to receive response: \(error)") finished = true return } //PROCESS DATA INTO CORE DATA finished = true }
  7. Network Conditions • Operations can report speeds • Control Performance

    via the Queue • Network Controller can react to conditions • Central location for canceling of actions • Single decision point for background processing
  8. Wrap up • Own your network code • Don’t put

    network code in view controllers • Keep all network code together • All UI should feed from Core Data • Disconnect data collection and data display