NSURLSession post:uploadTask和dataTask之间的区别 [英] NSURLSession post : difference between uploadTask and dataTask

查看:171
本文介绍了NSURLSession post:uploadTask和dataTask之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的两个例子:

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        config.HTTPAdditionalHeaders = ["Accept": "application/json",
                                        "Content-Type": "application/json",
                                        "User-Agent": UIDevice.currentDevice().model]


        var request = NSMutableURLRequest(URL: NSURL(string: "http://XXX"))
        request.HTTPMethod = "POST"

        let valuesToSend = ["key":value, "key2":value]
        var error: NSError?
        let data = NSJSONSerialization.dataWithJSONObject(valuesToSend, options:NSJSONWritingOptions.PrettyPrinted, error: &error)
        request.HTTPBody = data

        if error == nil {
            let task = NSURLSession(configuration: config).dataTaskWithRequest(request,
                completionHandler: {data, response, error in

                if error == nil {
                    println("received == \(NSString(data: data, encoding: NSUTF8StringEncoding))")
                }
            })

            task.resume()

        } else {
            println("Oups error \(error)")
        }

第二个

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        config.HTTPAdditionalHeaders = ["Accept": "application/json",
                                        "Content-Type": "application/json",
                                        "User-Agent": UIDevice.currentDevice().model]


        var request = NSMutableURLRequest(URL: NSURL(string: "http://XXX"))
        request.HTTPMethod = "POST"

        let valuesToSend = ["key":value, "key2":value]
        var error: NSError?
        let data = NSJSONSerialization.dataWithJSONObject(valuesToSend, options:NSJSONWritingOptions.PrettyPrinted, error: &error)

        if error == nil {

            let task = NSURLSession(configuration: config).uploadTaskWithRequest(request, fromData: data,
                completionHandler: {data, response, error in

                if error == nil {
                    println("received == \(NSString(data: data, encoding: NSUTF8StringEncoding))")
                }
            })

            task.resume()


        } else {
            println("Oups error \(error)")
        }

所以我想知道:这两个示例之间有什么区别?对于我的情况(简单的邮寄和接收)有什么好处

So I wonder : what are the differences between these twos examples and what about the better for my case ( simple post and reception )

这两个都没有背景吗?是吗?

The two are in background no ? So ?

推荐答案

来自

dataTaskWithRequest:

基于指定的URL请求对象创建HTTP请求. - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request 参数

Creates an HTTP request based on the specified URL request object. - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request Parameters

请求

一个对象,提供特定于请求的信息,例如URL, 缓存策略,请求类型以及正文数据或正文流.

An object that provides request-specific information such as the URL, cache policy, request type, and body data or body stream.

返回值

新的会话数据任务.

讨论

创建任务后,必须通过调用其履历表来启动它 方法.

After you create the task, you must start it by calling its resume method.

可用性

在iOS 7.0和更高版本中可用.

Available in iOS 7.0 and later.

声明为

NSURLSession.h


uploadTaskWithRequest:fromData:

为指定的URL请求对象创建一个HTTP请求,并 上传提供的数据对象. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData 参数

Creates an HTTP request for the specified URL request object and uploads the provided data object. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData Parameters

请求

一个NSURLRequest对象,提供URL,缓存策略,请求 类型,依此类推.此请求对象中的正文流和正文数据 被忽略.

An NSURLRequest object that provides the URL, cache policy, request type, and so on. The body stream and body data in this request object are ignored.

bodyData

请求的正文数据.

返回值

新的会话上传任务.

讨论

创建任务后,必须通过调用其resume来启动它 方法.

After you create the task, you must start it by calling its resume method.

可用性

在iOS 7.0和更高版本中可用.

Available in iOS 7.0 and later.

声明为

NSURLSession.h

此外, Ray Wenderlich 说:

NSURLSessionDataTask

NSURLSessionDataTask

此任务发出HTTP GET请求以从服务器提取数据.这 数据以NSData的形式返回.然后,您将转换此数据 正确的类型XMLJSONUIImageplist

This task issues HTTP GET requests to pull down data from servers. The data is returned in form of NSData. You would then convert this data to the correct type XML, JSON, UIImage, plist, etc.

NSURLSessionDataTask *jsonData = [session dataTaskWithURL:yourNSURL
      completionHandler:^(NSData *data,
                          NSURLResponse *response,
                          NSError *error) {
        // handle NSData
}];


NSURLSessionUploadTask

NSURLSessionUploadTask

需要将某些内容上传到Web服务时使用此类 使用HTTP POSTPUT命令.任务的委托也 允许您在传输过程中观察网络流量.

Use this class when you need to upload something to a web service using HTTP POST or PUT commands. The delegate for tasks also allows you to watch the network traffic while it's being transmitted.

上传图片:

NSData *imageData = UIImageJPEGRepresentation(image, 0.6);

NSURLSessionUploadTask *uploadTask =
  [upLoadSession uploadTaskWithRequest:request
                              fromData:imageData];

此处是从会话创建任务,并且图像以 NSData.还有使用文件或流进行上传的方法.

Here the task is created from a session and the image is uploaded as NSData. There are also methods to upload using a file or a stream.

但是,您的问题仍然模棱两可且过于笼统,因为您没有解释明确的特定问题,只需稍作搜索就可以轻松找到此信息.

However your question remains quite ambiguous and too broad, since you haven't explained an explicit, specific problem and you could easily find this information by searching a little bit.

这篇关于NSURLSession post:uploadTask和dataTask之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆