简体   繁体   English

如何快速设置Alamofire调用中的类变量值?

[英]How to set a class variable with value from Alamofire call in swift?

I am new to iOS development, and I have a class that I am using to retrieve data from a server. 我是iOS开发的新手,我有一个用于从服务器检索数据的类。 I would like to store a value from an Alamofire request as class variable for use with subsequent requests. 我想将Alamofire请求中的值存储为类变量,以用于后续请求。 I understand that Alamofire requests have completion handlers with them, but it is still not very clear to me how these work. 我了解Alamofire请求具有完成处理程序,但是我仍然不清楚这些如何工作。

In setSessionID , I would like to store the String from generateNewSessionID into sessionID . setSessionID ,我想将generateNewSessionID的字符串存储到sessionID This obviously isn't the correct way to do this, as I get an unwrapped nil optional error in the print statement. 这显然不是正确的方法,因为在print语句中出现了未包装的nil可选错误。

import Alamofire
import Foundation

class DataRetriever {
    private var sessionID: String?
    private let baseUrl: String?
    private let endPoints = ["session": "/session", "population": "/population/"]

    init() {
        let dict = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Config", ofType: "plist")!)
        baseUrl = dict!["baseUrl"] as? String
        setSessionID()
    }

    private func generateNewSessionID(completionHandler: (NSError?, String?) -> ()) {
         let params = [ "stuff": "stuff", "morestuff": "moreStuff" ]

        Alamofire.request(.POST, baseUrl! + endPoints["session"]!, parameters: params, encoding:ParameterEncoding.URL, headers: getSessionHeaders()).responseJSON { response in
            switch response.result{
            case .Success:
                completionHandler(nil, String(response.response!))
            case .Failure(let error):
                completionHandler(error, nil)
            }
        }
    }

    func setSessionID() {
        generateNewSessionID() { (error, session) in
            if error != nil {
                // handle error
            } else {
                self.sessionID = session
            }
        }

        print(self.sessionID!)
    }
}

I've looked through other examples, but I can't see how I would be able to do this within the scope of my class. 我浏览了其他示例,但看不到如何在我的课程范围内做到这一点。

In your setSessionID if you check if error != nil that's mean if theres an error handle it, so you should change it like this setSessionID如果您检查if error != nil是否表示有错误处理,那么就应该这样更改它

if error == nil {
   // No error
   self.sessionID = session
} else {
   //handle Error
}

You're actually printing the sessionID outside of your completion block, which means it's trying to print the value before the network request has completed. 您实际上是在完成块之外打印sessionID,这意味着它正在尝试在网络请求完成之前打印该值。 You need to move it inside your completion block like so: 您需要像这样将其移动到完成块内:

 func setSessionID() {
    generateNewSessionID() { (error, session) in
        if error != nil {
            // handle error
        } else {
            self.sessionID = session
        }

        // moved print here
        print(self.sessionID!)
    }
}

You should, of course, guard against the possibility that session could be nil: 您当然应该警惕会话可能为零的可能性:

guard let id = self.sessionID else {
    return
}

print(id)

But assuming it's not, the first code block should work. 但是假设不是,第一个代码块应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM