gpt4 book ai didi

ios - Twitter 用户图像解析 - Swift

转载 作者:行者123 更新时间:2023-11-29 00:58:04 25 4
gpt4 key购买 nike

我正在尝试使用以下代码从 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 为零

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

twitterphotoUrl actually have the link

有什么帮助吗???

最佳答案

我猜测您从 pbs.twimg.com URL 中收到了 ATS 异常,因此您没有获取数据,因此在强行打开数据时您会摔倒。您应该将该域添加到 ATS 异常(exception)列表中,如图所示 here , [在此处记录] ( https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html )(在该页面上搜索 NSExceptionDomain)并在许多其他地方进行了讨论。

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

关于ios - Twitter 用户图像解析 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37409962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com