简体   繁体   中英

Passing data to delegate in swift

I have this use case where a model object (eg class User) has few methods.

Some of the methods in the class require authentication (eg getProfile, getFriends,...).

   class User{

          var loginDelegate:LoginDelegate

          func getProfile{
              HTTPAsync.getProfile(payload){response in 
                     if response.status == 401 {
                           login(delegate)
                      }
               }


          func getFriends{
                 //similar code as above
                        login(delegate)
          }

Once, user is successfully logged in, I want to call respective functions (getFriends, getProfile, whichever invoked login).

I have been thinking to use delegate pattern. But since my class (user) has multiple methods that require login, I need to pass some data to delegate, which must be read after user is logged in to call the appropriate method.

I am new to Swift, and was wondering if I am going in the right path. Is there any other obvious way to achieve this pretty common problem.

在我的应用中,使用Url whiteList解决此问题,例如,当用户未登录并使用请求时,用户身份验证界面中的Url包含“ / users /”此字符串(或其他字符串)。这样的一个Url发出通知,由一个统一的班级接收这个通知,然后弹出登录框

I am new to Swift, and was wondering if I am going in the right path. Is there any other obvious way to achieve this pretty common problem.

Yes there are a couple of ways you might choose to solve this. e

  1. Define getter methods on your delegate protocol, if it is not your own delegate protocol you can use an extension to extend it's functionality.

  2. Create an Enumeration as an instance variable so you can set an enumeration value with in the login method that your other methods can access after the login method finishes.

  3. Change the login method to accept more parameters and returns a value\\object.

    For example:

    login(delegate: LoginDelegate, dictionaryOfOtherStuff: [String :AnyObject]?) -> (value_1: String, value_2 : [int])

I can only give an example since you have not stated exactly what needs to be available after the login method is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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