2016-07-08 42 views
0

我打Facebook的圖表來拉取用戶登錄時的基本用戶信息。我的問題是如何使用swift以最佳方式保存/提取信息它在此後繼續存在於子視圖控制器中(基本上每個登錄後都是)。舉例來說,我想在登錄屏幕(而不是在它)在我登錄視圖控制器我有這樣的相關代碼後仍繼續使用的個人資料相片的設置按鈕,整個應用程序:保存api Facebook數據,以便在不同的ViewController中使用swift iOS

let userImageView: UIImageView = { 
    let imageView = UIImageView() 

    return imageView 
}() 

let nameLabel: UILabel = { 
    let label = UILabel() 

    return label 
}() 

再後來:

func fetchProfile() { 
    let parameters = ["fields": "email, first_name, last_name, picture.type(large)"] 
    FBSDKGraphRequest(graphPath: "me", parameters: parameters).startWithCompletionHandler({ (connection, user, requestError) -> Void in 

     if requestError != nil { 
      print(requestError) 
      return 
     } 

     var _ = user["email"] as? String 
     let firstName = user["first_name"] as? String 
     let lastName = user["last_name"] as? String 

     self.nameLabel.text = "\(firstName!) \(lastName!)" 

     var pictureUrl = "" 

     if let picture = user["picture"] as? NSDictionary, data = picture["data"] as? NSDictionary, url = data["url"] as? String { 
      pictureUrl = url 

     } 

     let url = NSURL(string: pictureUrl) 
     NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in 
      if error != nil { 
       print(error) 
       return 
      } 

      let image = UIImage(data: data!) 
      dispatch_async(dispatch_get_main_queue(), {() -> Void in 
       self.userImageView.image = image 
      }) 

     }).resume() 

    }) 
} 

我需要做什麼來訪問我的第二個ViewController?根據我的理解,segues只有在第一個viewController中有一個物理屬性來幫助它們時纔有幫助。

感謝

回答

0

保存圖像將與文檔目錄爲核心的數據不能在檔案一樣大的圖像優化的最佳方式。你想在文檔目錄的照片保存爲這樣......

func saveImageDocumentDirectory(){ 
     let fileManager = NSFileManager.defaultManager() 
     let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent(*** Name of DocDir Image***) 
     let image = // *** Your Facebook Image *** 
     print(paths) 
     let imageData = UIImageJPEGRepresentation(image!, 0.5) 
     fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil) 
    } 

然後在您的視圖 - 控制(S)創建一個空的公衆形象var fbImage:UIImage()然後創建的getImage功能和代碼如下... ..

func getImage() 
{ 
      let fileManager = NSFileManager.defaultManager() 
      let imagePAth = (self.getDirectoryPath() as NSString).stringByAppendingPathComponent(*** Name of Your DocDir Image ***) 
      if fileManager.fileExistsAtPath(imagePath){ 
       self.fbImage.image = UIImage(contentsOfFile: imagePath) 
      }else{ 
       print("No Image Saved") 
      } 
     } 
相關問題