在继续

时间:2018-02-19 16:08:38

标签: swift nsurlsession nsurlrequest

我正在使用iOS Swift应用程序而我正在尝试获取网站的内容。问题是,当我运行代码时,在执行其他行之后返回响应对象。

我有这个:

public var response: Array<Any>?

public func myRequest(completion: @escaping (_ json: Any?, _ error: Error?)->()) {
    var request = URLRequest(url: self.url)
    request.httpBody = postString.data(using: .utf8)
    let t = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data,
        error == nil else {
            completion(nil, error)
            return
        }
        let json = try? JSONSerialization.jsonObject(with: data, options: [])
        if let dictionary = json as? [String : Any] {
            if (dictionary["ok"] as? String == "true") {
                self.response = dictionary["users"] as? Array<Any>
            }
        }
        completion(json, error)
    }
    t.resume()
}

然后:

func foo() {
    myRequest() { json, error in
        print(json)
    }
    print("I'm here!")
}

我得到了这个:

I'm here
{...} //JSON

问题是:为什么我在I'm here之前检索JSON?我该如何解决?

1 个答案:

答案 0 :(得分:0)

以下是一个示例(基于您的代码),了解如何让myRequest接受完成块,并在反序列化(或不反馈)JSON后调用它。

public func myRequest(completion: @escaping (_ json: Any?, _ error: Error?)->())
{
    var request = URLRequest(url: self.url)
    request.httpBody = postString.data(using: .utf8)
    let t = URLSession.shared.dataTask(with: request) 
    { data, response, error in
        guard let data = data,
                  error == nil else
        {
            completion(nil, error)
            return
        }
        let json = try? JSONSerialization.jsonObject(with: data, options: [])
        //Do other things
        completion(json, error)
    }
    t.resume()
}

以下是你如何称呼它:

func foo()
{
    myRequest()
        { json, error in
            // will be called at either completion or at an error.
        }
}

现在,如果你不是主线程,并且真的想等待你的myRequest()完成,那么就是这样的(有很多方法可以做到这一点,顺便说一句):

func foo()
{
    let group = DispatchGroup()
    group.enter()

    myRequest()
        { json, error in
            // will be called at either completion or at an error.
            group.leave()
        }
    group.wait() // blocks current queue so beware!
}