在http请求swift中保存会话 [英] save session in http request swift

查看:120
本文介绍了在http请求swift中保存会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中我正在使用JSON并且我最近进行了一次会话,因此如果我想为特定用户提供一些http请求来获取数据,则用户必须先登录(也由http请求使用)。当我输入登录网址然后输入接收数据的网址时,我会在Safari中获得
,它会根据需要执行此操作。
但在我的应用程序中,我首先调用login然后获取数据的url,但它可能在每个url请求中启动一个新会话,这导致我收到错误而没有收到数据。
我的网址请求函数是:

in my app I'm using JSON and I made a session recently so if I would like to make some http request to get data for a specific user, the user must log in before (also used by http request). in the safari when I entering the url's of login and then the url of receive data, it does that as needed. but in my app, I first call login and then the url for getting data, but it's probably starting a new session in every url request which leads me to get an error and not receive the data. my url request function is:

static func urlRequest (adress: String, sessionEnded: (NSDictionary->Void)?){
    println(adress)
    var urli = NSURL(string: adress)
    var request = NSURLRequest(URL: urli!)
    var rVal = "";
     self.task = NSURLSession.sharedSession().dataTaskWithURL(urli!) {(data, response, error) in
        var parseError: NSError?
        let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data,
            options: NSJSONReadingOptions.AllowFragments,
            error:&parseError)
        let po = parsedObject as NSDictionary
        if let a = sessionEnded{
            sessionEnded!(po)
        }
    }
    task!.resume()

}

提前感谢!!

推荐答案

你只共享了一半我们的难题,客户端代码。我们无法评论为什么应用程序无法更清楚地了解服务器API的内容。例如,一旦登录,后续查询如何确认请求来自有效会话。此外,您报告每个网址请求导致我收到错误。那么,你收到什么错误?关于您收到的确切错误/崩溃,您必须更加具体。顺便说一句,您是使用定义良好的API登录某些服务还是自己编写代码?

You have shared only half of the puzzle with us, the client code. We can't comment on why the app isn't working with a clearer picture of what the server API. For example, once you "log in", how do subsequent queries confirm that the request is coming from valid session. Furthermore, you report that "every url request which leads me to get an error". Well, what error do you receive? You have to be far more specific regarding the precise errors/crashes you are receiving. BTW, are you logging on to some service with a well-defined API or are you writing that code yourself, too?

话虽如此,我可能会建议对此方法进行一些改进:

Having said that, I might suggest a few refinements to this method:


  1. sessionEnded (我已将其重命名为 completionHandler 以符合非正式的标准命名约定),可能应该返回一个可选的 NSError 对象,所以调用者可以检测是否有错误。

  1. The sessionEnded (which I've renamed completionHandler to conform to informal standard naming conventions), probably should return an optional NSError object, too, so the caller can detect if there was an error.

你打开 sessionEnded 完成处理程序可以简化为使用

Your unwrapping of the sessionEnded completion handler can be simplified to use ?.

解析对象时,您也应该随意执行可选的强制转换。

When you parse the object, you should feel free to perform the optional cast, too.

您可能想要检测网络错误(在这种情况下 data nil )并返回网络 NSError 对象。

You probably want to detect a network error (in which case data would be nil) and return the network NSError object.

小点,但我可能还会将函数重命名为符合Co coa命名约定,使用动词来启动名称。也许类似 performURLRequest

Minor point, but I'd probably also rename the function to conform to Cocoa naming conventions, using a verb to start the name. Perhaps something like performURLRequest.

这是你的电话,但我倾向于方法返回 NSURLSessionTask ,以便调用者可以使用该任务对象(例如保存任务对象,以便它可以取消以后如果想要的话。)

This is your call, but I'd be inclined to have the method return the NSURLSessionTask, so that the caller could use that task object if it wanted to (e.g. save the task object so that it could cancel it later if it wanted to).

因此,产生的结果如下:

Thus, that yields something like:

func performURLRequest (address: String, completionHandler: ((NSDictionary!, NSError!) -> Void)?) -> NSURLSessionTask {
    let url = NSURL(string: address)
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        if data == nil {
            sessionEnded?(nil, error)
        } else {
            var parseError: NSError?
            let parsedObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error:&parseError) as? NSDictionary
            completionHandler?(parsedObject, parseError)
        }
    }
    task.resume()

    return task
}

你可以调用它:

performURLRequest("http://www.example.com/some/path") { responseDictionary, error in
    if responseDictionary == nil {
        // handle error, e.g.
        println(error)
        return
    }

    // use `responseDictionary` here
}

这篇关于在http请求swift中保存会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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