0

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???

ynamao
  • 106
  • 1
  • 16

2 Answers2

1

I would guess that you're getting an ATS exception from the pbs.twimg.com URL, so you're not getting the data, so you fall over when you force unwrap it. You should add that domain to the list of ATS exceptions as shown here, [documented here] (https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html) (search for NSExceptionDomain on that page) and discussed in many other places.

In addition to that, force unwrapping the results of URL calls is always a bad idea, since any number of things could prevent a data object being created. You should be using guard or if let statements in this case.

Community
  • 1
  • 1
jrturton
  • 118,105
  • 32
  • 252
  • 268
  • thank you , I did add this to info.plist file , and I no longer have a "NSURLSession/NSURLConnection HTTP" error now. but the image takes long time to show up! – ynamao May 24 '16 at 10:31
0

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

Jigar Tarsariya
  • 3,189
  • 3
  • 14
  • 38
  • thank you , it did work , but do have any idea why does it take so long to load the image? – ynamao May 24 '16 at 10:32
  • Obviously, directly assigning data to image it will take times. You can reduce time by assigning data in `async` method like : `dispatch_async(dispatch_get_main_queue(), { () -> Void in self.userImg.image = UIImage(image: imageData!) })` – Jigar Tarsariya May 24 '16 at 10:45