Twitter 用户图像解析 - Swift

Twitter user image Parse - Swift

我正在尝试使用此代码从 Twitter(解析- Twitter 登录)获取用户图像:

 if PFTwitterUtils.isLinkedWithUser(PFUser.currentUser()!) {

        let screenName = PFTwitterUtils.twitter()?.screenName!
        let requestString = NSURL(string: "https://api.twitter.com/1.1/users/show.json?screen_name=" + screenName!)
        let request = NSMutableURLRequest(URL: requestString!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
        PFTwitterUtils.twitter()?.signRequest(request)
        let session = NSURLSession.sharedSession()

        session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
            print(data)
            print(response)
            print(error)

            if error == nil {
                var result: AnyObject?
                do {
                    result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
                } catch let error2 as NSError? {
                    print("error 2 \(error2)")
                }

                let names: String! = result?.objectForKey("name") as! String
                let separatedNames: [String] = names.componentsSeparatedByString(" ")

                //self.firstName = separatedNames.first!
                //self.lastName = separatedNames.last!

                let urlString = result?.objectForKey("profile_image_url_https") as! String
                let hiResUrlString = urlString.stringByReplacingOccurrencesOfString("_normal", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
                let twitterPhotoUrl = NSURL(string: hiResUrlString)
                let imageData = NSData(contentsOfURL: twitterPhotoUrl!)
                let twitterImage: UIImage! = UIImage(data:imageData!)
                self.userImg = UIImageView(image: twitterImage)
            }
        }).resume()
    }

但是 imageData 是 nil

  let imageData = NSData(contentsOfURL: twitterPhotoUrl!) 
  let twitterImage: UIImage! = UIImage(data:imageData!)

twitterphotoUrl actually have the link

有什么帮助吗???

我猜你是从 pbs.twimg.com URL 得到了一个 ATS 异常,所以你没有得到数据,所以当你强行解包时你摔倒了。您应该将该域添加到 ATS 异常列表中,如 , [documented here] (https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html) 所示(在该页面上搜索 NSExceptionDomain)并在许多其他地方进行了讨论。

除此之外,强制解包 URL 调用的结果总是一个坏主意,因为任何数量的事情都可能阻止创建数据对象。在这种情况下,您应该使用 guard 或 if let 语句。

试试下面的代码,

if let imageData = NSData(contentsOfURL: twitterPhotoUrl!)
{
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.userImg.image = UIImage(image: imageData!)
     })
}

希望这会奏效