Alamofire GET请求仅在安装后调用一次 - Swift

时间:2018-05-23 00:45:29

标签: ios swift get alamofire swifty-json

我正在尝试使用AlamofireSwiftyJSON进行网络请求来解析并向数组添加JSON对象。但是它只在我安装应用程序后第一次运行。如果我终止该应用并再次输入,则不会调用GET请求。我不知道是什么让它只工作一次。

func getSubreddits() {

    guard let requestURL = URL(string: "https://oauth.reddit.com/subreddits/mine/subscriber?limit=100"),
        let token = KeychainWrapper.standard.string(forKey: "oauthToken") else { return }

    print("my retrieved token is \(token)")
    let headers = ["User-Agent" : "ios:com.GK.voyager:v1.0 (by /u/ZypherXX)",
                   "Content-Type" : "application/x-www-form-urlencoded",
                   "Authorization" : "bearer \(token)"]

    print(headers)

    Alamofire.request(requestURL, method: .get, parameters: [:], encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in

        switch response.result {
        case .success:
            if let value = response.result.value {
                let json = JSON(value) //Don't forget to import SwiftyJSON
                self.parse(json: json)
            }
        case .failure:
            if let error = response.result.error {
                print(error)
            }
        }
    }
}

func parse(json: JSON) {
    for result in json["data"]["children"].arrayValue {
        let subreddit = result["data"]["subreddit"].stringValue
        let description = result["data"]["description"].stringValue
        let name = result["data"]["display_name"].stringValue
        let subscribers = result["data"]["subscribers"].intValue
        let subObject = Subreddit(subreddit: subreddit, name: name, description: description, subscribers: subscribers)
        subreddits.append(subObject)
      print(subreddits)
    }
    tableView.reloadData()
}

0 个答案:

没有答案