【问题标题】:working with synchronous post methods in swift快速使用同步发布方法
【发布时间】:2018-02-12 17:01:58
【问题描述】:

我有一个 iOS 应用程序,我从服务器获取我的信息,问题是我使用的所有请求都没有工作,因为代码执行正在退出代码,然后从服务器获取响应,或者可能它失败了,无论如何这是我迄今为止尝试过的:

let manager = AFHTTPSessionManager()

        manager.post("www.myapps.com/api/Files/getFiles?folderId=6", parameters: nil, progress: nil, success: { (task: URLSessionTask, responseObject) in
            if let response = responseObject as? [String:Any],
                let medias = response["medias"] as? [String:Any] {

                locked = false
                let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

                let url      = NSURL(fileURLWithPath: documentsPath)
                let contentFile = url.appendingPathComponent("Content.json")
                if let data = try? JSONSerialization.data(withJSONObject: medias) {
                    try? data.write(to: contentFile!, options: .atomic)
                }

                let data = try! Data(contentsOf: contentFile!)
                self.jsonData =  JSON(data:data)
                self.categoriesCount = self.jsonData["categories"].count
                print(self.categoriesCount)
            }
        },failure: { (operation: URLSessionTask!, NSError) in
            print(NSError.localizedDescription)
        })
    while locked {
        wait()
    }
}

func wait()
{
    DispatchQueue.main.async {
       RunLoop.current.run(mode: RunLoopMode.defaultRunLoopMode, before: NSDate(timeIntervalSinceNow: 1) as Date)
    }

}

请记住,如果我直接在浏览器中使用我的 URL,我会得到一个响应,这意味着它正在运行,但是在我的应用程序中,有什么想法会出错吗?

【问题讨论】:

  • 您发布的代码到底有什么问题?也许你需要展示这段代码的全部功能。
  • 问题是这总是失败,可能是由于在此之后执行代码而我仍然没有响应,或者我使用的 post 方法有问题。
  • 失败怎么办?您需要在问题中提供有用的详细信息。有错误吗?把它们放在你的问题中。代码是否根本没有按照您期望的方式执行?然后清楚地描述它在哪些方面是不正确的。
  • 不要等待。使用完成处理程序Here 是无数示例之一。
  • 不要同步发帖。不要wait。正确地做事。

标签: ios swift httprequest


【解决方案1】:

我通过使用Alamofire同步方法解决了以下问题:

let response = Alamofire.request("http://www.appsandgamesinc.com/api/Files/getFiles", method: .post, parameters: ["folderId": "6"]).responseJSON(options: .allowFragments)
        if let json = response.result.value {
            print(json)
}

【讨论】:

    猜你喜欢
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2012-09-07
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多