如何在Swift中的函数外传递已编辑的变量

问题描述

我试图允许用户使用DBChooser从DropBox应用中选择图片。因此,当用户单击按钮时,它会将他们重定向到他们选择图像的DropBox应用。然后,DropBox会将用户以该图像的信息以数组的形式重定向回我的应用程序。我只想从该数组中获取图像的“链接”,然后将其分配给要在我的代码中其他地方使用的值。

为此,我设置了AppDelegate,StringExtension和URLExtension来操纵数组。

下面是我遇到的问题。这整个代码块都可以工作,当DropBox用户发送回我的应用程序时,我什至可以在控制台中打印出链接。但是,当我在函数外部使用变量dbLink时,得到的是nil而不是链接。我的猜测是未从函数getUrlFromArray传递变量dbLink。我已经在互联网上进行搜索,但是找不到不会导致更多错误解决方案。我的其余代码是否有问题,或者我在功能上做错了什么?

class ViewController: UIViewController {
    
    var dbLink: String?
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
    }
    
    internal func getUrlFromArray(_ dict: JSON ) {
        
        dbLink = (dict["link"]! as! String)
        print(dbLink!)
        
    }
    
    @IBAction func dbChooserBtnpressed(_ sender: Any) {
        let appDelegate = UIApplication.shared.delegate as? AppDelegate
        appDelegate?.chooser.open(for: DBChooserLinkTypeDirect,from: self,completion: { (val) in })
    }
    
}

下面是与上面的代码相关的所有其他代码

StringExtension.swift

import Foundation

extension String {
    func toJSON() -> Any {
        if let data = self.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data,options: [])
            } catch {
                print(error.localizedDescription)
            }
        }
        return [:]
    }
}

URLExtension.swift

public typealias JSON = [String: Any]

extension URL {

    public var queryParameters: [String: String]? {
        guard let components = URLComponents(url: self,resolvingAgainstBaseURL: true),let queryItems = components.queryItems else {
            return nil
        }
        var parameters = [String: String]()
        for item in queryItems {
            parameters[item.name] = item.value
        }

        return parameters
    }

}

AppDelegate

class AppDelegate: UIResponder,UIApplicationDelegate {

    var window: UIWindow?
    
    func application(_ app: UIApplication,open url: URL,options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        if chooser.handleOpen(url) {
            if let files = url.queryParameters?["files"]?.toJSON() as? [JSON] {
                let dictDeepLink = files[0]
                ViewController().getUrlFromArray(dictDeepLink)
            }
            return true
        }
        return false
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)