swift network

https://github.com/Narsail/OneTheMap

 

1.

class NetworkService {
    
    private var task: NSURLSessionDataTask?
    private var successCodes: Range<Int> = 200..<299
    private var failureCodes: Range<Int> = 400..<499
    
    enum Method: String {
        case GET, POST, PUT, DELETE
    }
    
    func request(url: NSURL, method: Method,
                 params: [String: AnyObject]? = nil,
                 headers: [String: String]? = nil,
                 success: ((NSData?) -> Void)? = nil,
                 failure: ((data: NSData?, error: ErrorType?, responseCode: Int) -> Void)? = nil) {
    
        
        let mutableRequest = NSMutableURLRequest(URL: url, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
                                                 timeoutInterval: 10.0)
        mutableRequest.allHTTPHeaderFields = headers
        mutableRequest.HTTPMethod = method.rawValue
        if let params = params {
            mutableRequest.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
        }
        
        let session = NSURLSession.sharedSession()
        task = session.dataTaskWithRequest(mutableRequest, completionHandler: { data, response, error in
            // Decide whether the response is success or failure and call
            // proper callback.
            
            var responseCode = 0
            
            if let response = response as? NSHTTPURLResponse {
                responseCode = response.statusCode
            }
            
            if responseCode >= 300 {
                failure?(data: data, error: error, responseCode: responseCode)
                return
            }
            
            if data != nil && error == nil {
                success?(data!)
            } else {
                failure?(data: data, error: error, responseCode: responseCode)
            }
        })
        
        task?.resume()
    }
    
    func cancel() {
        task?.cancel()
    }
}

2.

public class SessionPOSTOperation: AuthenticationServiceOperation {
    
    private let requestItem: SessionPOSTRequest
    
    internal var success: ((session: String) -> Void)?
    internal var failure: ((error: ErrorType) -> Void)?
    
    internal init(request: SessionPOSTRequest, backendConfiguration: BackendConfiguration, success: ((session: String) -> Void)? = nil, failure: ((error: ErrorType) -> Void)? = nil) {
        self.requestItem = request
        self.success = success
        self.failure = failure
        super.init(backendConfiguration: backendConfiguration)
    }
    
    public override func start() {
        super.start()
        service.request(self.requestItem, success: self.handleSuccess, failure: self.handleFailure)
    }
    
    private func handleSuccess(response: AnyObject?) {
        do {
            let sessionID = try SessionResponseMapper.process(response)
            self.success?(session: sessionID)
            self.finish()
        } catch {
            handleFailure(error)
        }
    }
    
    private func handleFailure(error: ErrorType) {
        self.failure?(error: error)
        self.finish()
    }
    
}

3.

final class UdacityAPI {
    
    internal static let shared = UdacityAPI()
    
    let backendQueue = NSOperationQueue()
    let configuration: BackendConfiguration
    
    private init() {
        configuration = BackendConfiguration(baseURL: NSURL(string: "https://www.udacity.com/api/")!)
    }
    
    /// Login through the Udacity API and fetch the Session ID
    
    func login(withEmail email: String, withPassword password: String, withCompletionHandler completionHandler: ((sessionID: String) -> Void)? = nil, withErrorHandler errorHandler: ((error: ErrorType) -> Void)? = nil) {
        let loginRequest = SessionPOSTRequest(username: email, password: password)
        let loginOperation = SessionPOSTOperation(request: loginRequest, backendConfiguration: configuration, success: { sessionID in
            completionHandler?(sessionID: sessionID)
        }, failure: { error in
            errorHandler?(error: error)
        })
        backendQueue.addOperation(loginOperation)
    }
    

    
}

 

posted @ 2016-09-28 11:53  lianhuaren  阅读(74)  评论(0编辑  收藏  举报