有关NSURLSession和NSURLSessionDataDelegate的问题

时间:2015-01-22 03:26:31

标签: ios swift nsurlsession

我最近一直在研究NSURLSession的子类来处理我的所有API请求,但是我遇到了一些问题。首先,返回的数据可以放在字典数组中,也可以放在普通数组中。我已经尝试使用AnyObject来解决这个问题,但这不起作用。其次,由于我不知道何时接收数据取决于连接所需的时间,我如何将数据传递到视图控制器?可能是一个循环?我不太确定。

//
//  Session.swift
//  Networking
//
//  Created by jkaufman on 1/19/15.
//  Copyright (c) 2015 jkaufman. All rights reserved.
//

import Foundation

public enum Method: String {
    case POST = "POST"
}

class Session: NSObject, NSURLSessionDataDelegate {
    let domain = "https://example.com/"
    var request: NSMutableURLRequest

    init(url: String, method: Method!, parameters: [String]!) {
        request = NSMutableURLRequest(URL: NSURL(string: domain + url)!)

        if(method != nil) {
            request.HTTPMethod = method.rawValue
        }

        if(parameters != nil) {
            var body: NSString = ""
            for var i = 0; i < parameters.count; i++ {
                if(i == 0) {
                    body = parameters[i]
                } else {
                    body = body + "&" + parameters[i]
                }
            }
            request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)
        }
    }

    func activateRequest() {
        let task = NSURLSession(configuration: .defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue()).dataTaskWithRequest(request)
        task.resume()
    }

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
        var err: NSError?
        var receivedData: AnyObject!
        receivedData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as AnyObject?
        println(data)
        println(receivedData)
    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
        println(totalBytesSent)
        println(totalBytesExpectedToSend)
    }

}

0 个答案:

没有答案