ynamao ynamao - 6 months ago 28
iOS Question

Twitter user image Parse - Swift

I'm trying to get user image from twitter(parse- twitter login) using this code :

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()
}


but it imageData is nil

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


twitterphotoUrl actually have the link

any help???

Answer

Try with below code,

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

Hope this will work

Comments