【问题标题】:Alamofire not executing correctly in SwiftAlamofire 在 Swift 中无法正确执行
【发布时间】:2016-04-04 00:21:41
【问题描述】:

我有一个 Alamofire 请求,假设下载一个文件,但它不会执行它自己的代码。这是 Alamofire 代码:

var testNumbers: Int = 0
var testString: String = "Hi"
Alamofire.download(.GET, "http://www.sayweee.com/admin_groupbuy/export_deal_orders/71w4o?format=csv") { temporaryURL, response in
            
            let fileManager = NSFileManager.defaultManager()
            let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
            let pathComponent = response.suggestedFilename  

            print("1")
            testNumbers = 1  

            print(directoryURL.URLByAppendingPathComponent(pathComponent!)) 

            print("blah")
            testString = "blah"
            print("2")
            testNumbers = 2  

            return directoryURL.URLByAppendingPathComponent(pathComponent!)
            
        }
print(testNumbers)
print(testString)

执行此代码将在控制台中打印:

 0
 Hi

我很确定这意味着{} 中的代码没有被执行。我读过另一个关于这个主题的文章,并了解到 Alamofire 是“异步的”,正如他们在this post 中所说的那样。我试图摆脱viewDidLoad() 方法和viewDidAppear() 方法中的所有内容,并确保我没有任何无限循环。即使在那之后,结果也是一样的。关于为什么会发生在我身上的任何想法或建议?我试图在这里和谷歌上查看,但我只找到了一篇与这个主题相关的帖子,就是上面链接的那个。

【问题讨论】:

  • 它工作正常,检查正确

标签: ios swift asynchronous alamofire


【解决方案1】:

首先我把你的代码放到Demo Alamofire中运行,发现运行结果和你说的一样,如下图: 0 Hi 2015-12-30 14:31:29.873 iOS Example[3966:142688] App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

根据提示你会看到问题: App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

解决方法如下(在项目文件“info.plist”中): In project's "info.plist" file to add a "NSAppTransportSecurity" dictionary, an element is added in the dictionary.Key for "NSAllowsArbitraryLoads", the value is: YES, make it back to the HTTP protocol for the time being.

问题解决链接:

Transport security has blocked a cleartext HTTP

最终结果如下:

0 Hi 1 file:///Users/yangshebing/Library/Developer/CoreSimulator/Devices/151CB429-29B3-46D0-AFF5-37D5B8D9E4FC/data/Containers/Data/Application/756A32D1-64C5-48CF-B652-D3009D80780D/Documents/71w4o.html blah 2

具体问题可以去查询苹果官方文档,查询iOS9 ATS适配问题。

希望能帮到你!

【讨论】:

  • 谢谢。即使您的回答没有帮助我解决问题,因为我的问题不同,但我感谢您为测试和解释问题所做的努力。在显示打印命令之前,我的程序实际上遇到了另一个错误。那停止了程序。现在我添加了一个while循环来等待下载完成,然后再继续,所以现在它可以工作了。尽管如此,您的回答可能会对该主题的未来访问者有所帮助。谢谢。
最近更新 更多