0

我花了很长时间在谷歌上搜索一个我似乎一辈子都找不到的特定产品解决方案,所以我来 Stack Overflow 寻求帮助。

我在一所未提及的公立大学工作,其中要求某些新生群体购买一台新笔记本电脑,他们拥有的选项之一是 13 英寸 Macbook Pro 的特定配置。我们预测将有大约 1,800 名学生在 8 月秋季学期开始之前的几个月内购买这些 Macbook。

我们遇到的问题是他们需要使用某些仅在 Windows 中可用的特定软件。我们找到了一个产品解决方案,它运行一个简单的 .dmg 文件并对现有硬盘进行分区,以便在 Boot Camp 中安装一个预配置的 Windows 映像,其中包括此所需的软件。通过这种方式,学生不需要执行任何超出其技术知识范围的任务,因为 Boot Camp 有时会有点令人困惑。

我正在寻找的解决方案是执行以下操作的应用程序或方法;

  1. 下载可能很大的 .dmg 文件(超过 40 GB),学生无需输入任何输入,例如文件在 Internet 上的位置
  2. 通过 md5 校验和验证文件
  3. 如果可能,自动执行该 .dmg 文件

或者这是我需要了解 Swift/Objective-C 才能通过开发自己来完成的事情?

4

1 回答 1

3

基本上,是的,你需要一些 Swift / Cocoa 框架的语言来做到这一点。您也可以随时使用另一种语言(例如 Python)来执行此操作。

  1. 下载文件。您可以使用一个简单的下载器类来做到这一点,如下所示:

    class HTTP {
        static func download(download_path: NSURL, save_path: NSURL, completion: ((NSError?, NSData?) -> Void)) {
            let req = NSMutableURLRequest(URL: download_path)
            req.HTTPMethod = "GET"
            NSURLSession.sharedSession().dataTaskWithRequest(req) { data, response, error in
                if error != nil {
                    //Downloading file failed
                    completion(error, nil)
                } else {
                    //Downloaded file
                    do {
                        //Write data to file:
                        if data != nil {
                            try data!.writeToFile(save_path.absoluteString + "file.dmg", options: [])
                            completion(nil, data!)
                        } else {
                            completion(NSError(domain: "Downloaded file null", code: -1, userInfo: nil), nil)
                        }
    
                    } catch {
                        completion(NSError(domain: "Could not write to file", code: -1, userInfo: nil), nil)
                    }
                }
            }.resume()
        }
    }
    
    //Usage: 
    HTTP.download(NSURL(string:"http://www.example.com/file.dmg")!, save_path:  NSURL(string: "/Users/username/Desktop/")!) {
        error, data in
    
        //Check if there's an error or data is null, if not continue to step 2
    }
    
  2. 检查 MD5 校验和。使用CommonCrypto Library计算文件数据的 MD5:

    //Usage:
    "contents-of-file".MD5
    
  3. 要运行 DMG,请查看从 swift 运行终端命令以及如何从终端运行 DMG 文件。或者,您可以使用Applescript 运行 DMG从 swift 调用该脚本

使用上述方法的完整示例:

HTTP.download(NSURL(string:"http://www.example.com/file.dmg")!, save_path: NSURL(string: "/Users/username/Desktop/")!) {
    error, data in
    if error == nil {
        guard data != nil else {
            //Data is nil
        }
        if String(data: data!, encoding: NSUTF8StringEncoding)!.md5() == /* Other MD5 value to check */ {
            //MD5 checksum completed. Use whatever method here to execute the DMG
            executeDMG(NSURL(string: "/Users/username/Desktop/file.dmg")!)
        }

    } else {
        //Couldn't download file
        //Info: error.localizedDescription property
    }
}
于 2016-05-17T22:14:00.837 回答