Swift Instagram API用户名未显示在标签上

时间:2019-06-28 11:31:57

标签: ios swift api instagram-api

我只是想使用Instagram API创建一个iOS应用,然后我才能看到用户个人资料。 我刚刚在我的Xcode项目上编写了此代码以制作iOS应用。

这是代码:-

    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
        signInRequest()
    }

    func signInRequest() {
        let getURL = String(format: "%@?client_id=%@&redirect_uri=%@&response_type=token&scope=%@&DEBUG=True", arguments: [API.INSTAGRAM_AUTHURL,API.INSTAGRAM_CLIENT_ID,API.INSTAGRAM_REDIRECT_URI,API.INSTAGRAM_SCOPE])
        let request = URLRequest.init(url: URL.init(string: getURL)!)
        webView.loadRequest(request)
    }

    func checkRequestForCallbackURL(request: URLRequest) -> Bool {

        let requestURLString = (request.url?.absoluteString)! as String
        if requestURLString.hasPrefix(API.INSTAGRAM_REDIRECT_URI) {
            let range: Range<String.Index> = requestURLString.range(of: "#access_token=")!
            handleAuth(authToken: requestURLString.substring(from: range.upperBound))
            return false
        }
        return true
    }
    func handleAuth(authToken: String) {
        let url = String(format: "https://api.instagram.com/v1/users/self/?access_token=%@", authToken)
        let request: NSMutableURLRequest = NSMutableURLRequest(url: URL(string: url)!)
        request.httpMethod = "GET"
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData



        let session = URLSession(configuration: .default)

        session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
            if let data = data {
                let json = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary
                let strFullName = (json?.value(forKey: "data") as AnyObject).value(forKey: "full_name") as! String


                let secondVC: SecondViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "secondSeg") as! SecondViewController

                secondVC.text = strFullName

                self.present(secondVC
                    , animated: true, completion: nil)

            }
        }.resume()
    }

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        return checkRequestForCallbackURL(request: request)
    }
}

我的问题是,当我运行我的应用并想要查看我在标签上看不到的instagram用户名时。

我看不到用户(全名,用户名,关注者等)

这是第二个VC代码。

    var text: String = ""

    @IBOutlet weak var userNameLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        userNameLabel?.text = text
    }

1 个答案:

答案 0 :(得分:0)

我相信您的viewdidload函数会在更新文本变量之前被调用

尝试更换:

var text: String = ""

使用:

var text: String = "" {
    didSet {
        userNameLabel?.text = text
    }
}