2016-03-30 22 views
0

Sürekli olarak arka planda çalışan ve bir dosyaya veri yazması gereken bir uygulama var. Bazen dosyaya yazılan kısmi bir kayıt buluyorum, bu yüzden uygulama eklendiyse bile herhangi bir yazma işlemini tamamlama şansının olacağını garanti etmek için ek bir kod ekledim.Arka planda iOS'taki bir dosyaya nasıl veri yazılır

Buradaki kod şu ana kadar çalışıyor ve işe yarıyor gibi görünüyor, ancak kullandığım API'lerin bu iş için en iyisi olup olmadığından emin değilim. Örneğin, dosyayı her seferinde dosyanın sonuna kadar aramak zorunda kalmamak için dosyayı açmanın ve açık tutmanın daha iyi bir yolu var mıdır?

Görevlerin arka plan görevi olarak işaretlenmesiyle ilgili yaklaşım, iOS'un görevin tamamlanmasına izin verdiğinden emin olmak için doğrudur - saniyede bir kez yürütülür.

/// We wrap this in a background task to ensure that task will complete even if the app is switched to the background 
/// by the OS 
func asyncWriteFullData(dataString: String, completion: (() -> Void)?) { 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { 

     let taskID = self.beginBackgroundUpdateTask() 

     self.writeFullData(dataString) 

     self.endBackgroundUpdateTask(taskID) 

     if (completion != nil) { 
      completion!() 
     } 

    }) 
} 
func beginBackgroundUpdateTask() -> UIBackgroundTaskIdentifier { 
    return UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({}) 
} 

func endBackgroundUpdateTask(taskID: UIBackgroundTaskIdentifier) { 
    UIApplication.sharedApplication().endBackgroundTask(taskID) 
} 
/// Write the record out to file. If the file does not exist then 
/// create it. 
private func writeFullData(dataString: String) { 


    let filemgr = NSFileManager.defaultManager() 

    if let filePath = self.fullDataFilePath { 

    if filemgr.fileExistsAtPath(filePath) { 

     if filemgr.isWritableFileAtPath(filePath) { 

      let file: NSFileHandle? = NSFileHandle(forUpdatingAtPath: filePath) 

      if file == nil { 
       // This is a major problem so best notify the User 
       // How are we going to handle this type of error ? 
       DebugLog("File open failed for \(self.fullDataFilename)") 
       AlertManager.sendActionNotification("We have a problem scanning data, please contact support."); 

      } else { 
       let data = (dataString as 
        NSString).dataUsingEncoding(NSUTF8StringEncoding) 
       file?.seekToEndOfFile() 
       file?.writeData(data!) 
       file?.closeFile() 
      } 

     } else { 
      //print("File is read-only") 
     } 

    } else { 
     //print("File not found") 

     if createFullDataFile() { 
      // Now write the data we were asked to write 
      writeFullData(dataString) 
     } else { 
      DebugLog("Error unable to write Full Data record") 
     } 

    } 
    } 
} 
+0

şey NSOutputStream açıkken iOS veya kullanıcı uygulamayı öldürürse nasıl çalışacak? WriteDataToFile – nielsbot

cevap

İlgili konular